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

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

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

import { GET } from "./route";

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

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

describe("GET /api/location/regeo", () => {
  it("returns reverse geocoded location", async () => {
    mockReverseGeocode.mockResolvedValue({
      name: "黄浦区 南京东路街道 人民广场",
      formatted: "上海市黄浦区人民大道",
    });

    const req = createRequest("/api/location/regeo?lat=31.23&lng=121.47");
    const res = await GET(req, mockCtx);
    const { status, data } = await parseJsonResponse(res);

    expect(status).toBe(200);
    expect(data.name).toContain("黄浦区");
    expect(data.formatted).toBe("上海市黄浦区人民大道");
  });

  it("returns null name when API returns no result", async () => {
    mockReverseGeocode.mockResolvedValue({ name: null, formatted: null });

    const req = createRequest("/api/location/regeo?lat=31.23&lng=121.47");
    const res = await GET(req, mockCtx);
    const { data } = await parseJsonResponse(res);
    expect(data.name).toBeNull();
  });

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

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

    const req = createRequest("/api/location/regeo?lat=31.23&lng=121.47");
    const res = await GET(req, mockCtx);
    expect(res.status).toBe(503);
  });
});
