import { describe, it, expect, vi, beforeEach } from "vitest";
import { prismaMock, resetPrismaMock } from "@/__tests__/helpers/prisma-mock";
import { createRequest, parseJsonResponse } from "@/__tests__/helpers/api-test-utils";
import { TEST_BLINDBOX_IDEA } from "@/__tests__/helpers/fixtures";
import { ApiError } from "@/lib/api";

vi.mock("@/lib/auth", () => ({
  getAuthUserId: vi.fn().mockResolvedValue("user-1"),
}));

vi.mock("@/lib/blindbox", () => ({
  requireMembership: vi.fn().mockResolvedValue({}),
}));

vi.mock("@/lib/ai", () => ({
  tagIdea: vi.fn().mockResolvedValue({
    category: "outdoor",
    timeSlot: "morning",
    estimatedMinutes: 120,
    costLevel: "free",
    intensity: "active",
    needsBooking: false,
    searchQuery: "公园",
    searchType: "category",
  }),
}));

import { POST } from "./route";
import { getAuthUserId } from "@/lib/auth";

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

beforeEach(() => {
  resetPrismaMock();
  vi.mocked(getAuthUserId).mockResolvedValue("user-1");
});

describe("POST /api/blindbox/retag", () => {
  it("retags untagged ideas and returns count", async () => {
    const untaggedIdea = { ...TEST_BLINDBOX_IDEA, category: null };
    prismaMock.blindBoxIdea.findMany.mockResolvedValue([untaggedIdea] as never);
    prismaMock.blindBoxIdea.update.mockResolvedValue(TEST_BLINDBOX_IDEA as never);

    const req = createRequest("/api/blindbox/retag", {
      method: "POST",
      body: { roomId: "bb-room-1" },
    });
    const res = await POST(req, mockCtx);
    const { status, data } = await parseJsonResponse(res);

    expect(status).toBe(200);
    expect(data.retagged).toBe(1);
    expect(data.total).toBe(1);
  });

  it("returns 0 when no untagged ideas", async () => {
    prismaMock.blindBoxIdea.findMany.mockResolvedValue([] as never);

    const req = createRequest("/api/blindbox/retag", {
      method: "POST",
      body: { roomId: "bb-room-1" },
    });
    const res = await POST(req, mockCtx);
    const { status, data } = await parseJsonResponse(res);

    expect(status).toBe(200);
    expect(data.retagged).toBe(0);
  });

  it("returns 401 when not authenticated", async () => {
    vi.mocked(getAuthUserId).mockRejectedValueOnce(new ApiError("请先登录", 401));
    const req = createRequest("/api/blindbox/retag", {
      method: "POST",
      body: { roomId: "bb-room-1" },
    });
    const res = await POST(req, mockCtx);
    expect(res.status).toBe(401);
  });
});
