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

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

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

import { GET } from "./route";

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

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

describe("GET /api/location/suggest", () => {
  it("returns suggestions", async () => {
    mockGetInputTips.mockResolvedValue([
      {
        id: "tip-1",
        name: "人民广场",
        district: "黄浦区",
        address: "人民大道",
        lat: 31.2304,
        lng: 121.4737,
      },
    ]);

    const req = createRequest("/api/location/suggest?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("人民广场");
  });

  it("returns empty for no keywords", async () => {
    const req = createRequest("/api/location/suggest");
    const res = await GET(req, mockCtx);
    const { data } = await parseJsonResponse(res);
    expect(data).toEqual([]);
  });

  it("filters tips without location", async () => {
    mockGetInputTips.mockResolvedValue([
      { id: "tip-1", name: "有位置", district: "", address: "", lat: 31.2, lng: 121.4 },
    ]);

    const req = createRequest("/api/location/suggest?keywords=test");
    const res = await GET(req, mockCtx);
    const { data } = await parseJsonResponse(res);
    expect(data).toHaveLength(1);
    expect(data[0].name).toBe("有位置");
  });

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

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