import { describe, it, expect, vi, beforeEach } from "vitest";
import { createRequest, parseJsonResponse } from "@/__tests__/helpers/api-test-utils";

vi.mock("@/lib/prisma", () => ({ prisma: {} }));

const mockSearchPlaceText = vi.fn();
vi.mock("@/lib/amap", () => ({
  searchPlaceText: (...args: unknown[]) => mockSearchPlaceText(...args),
}));

import { GET } from "./route";

const mockCtx = { params: Promise.resolve({}) };

beforeEach(() => {
  vi.clearAllMocks();
});

describe("GET /api/location/search", () => {
  it("returns search results", async () => {
    mockSearchPlaceText.mockResolvedValue([
      {
        id: "poi-1",
        name: "星巴克",
        address: "南京路1号",
        lat: 31.2,
        lng: 121.4,
        rating: 4.5,
        cost: 40,
      },
    ]);

    const req = createRequest("/api/location/search?keywords=星巴克");
    const res = await GET(req, mockCtx);
    const { status, data } = await parseJsonResponse(res);

    expect(status).toBe(200);
    expect(data).toHaveLength(1);
    expect(data[0].name).toBe("星巴克");
    expect(data[0].lat).toBe(31.2);
    expect(data[0].lng).toBe(121.4);
  });

  it("returns empty when no results", async () => {
    mockSearchPlaceText.mockResolvedValue([]);

    const req = createRequest("/api/location/search?keywords=不存在的地方");
    const res = await GET(req, mockCtx);
    const { data } = await parseJsonResponse(res);
    expect(data).toEqual([]);
  });

  it("returns 400 when keywords missing", async () => {
    const req = createRequest("/api/location/search");
    const res = await GET(req, mockCtx);
    expect(res.status).toBe(400);
  });

  it("returns 503 when API unavailable", async () => {
    const { ApiError } = await import("@/lib/api");
    mockSearchPlaceText.mockRejectedValue(new ApiError("位置服务暂时不可用，请稍后重试", 503));

    const req = createRequest("/api/location/search?keywords=test");
    const res = await GET(req, mockCtx);
    expect(res.status).toBe(503);
  });
});
