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 { ApiError } from "@/lib/api";

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

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

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

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

describe("GET /api/blindbox/rooms", () => {
  it("returns user rooms list", async () => {
    prismaMock.blindBoxMember.findMany.mockResolvedValue([
      {
        room: {
          id: "bb-room-1",
          code: "ABC123",
          name: "周末",
          creatorId: "user-1",
          _count: { members: 2, ideas: 5 },
          members: [
            { user: { id: "user-1", username: "test", avatar: "🐱" } },
          ],
          ideas: [{ content: "去公园", createdAt: new Date() }],
        },
        joinedAt: new Date(),
      },
    ] as never);

    prismaMock.blindBoxIdea.groupBy = vi.fn().mockResolvedValue([
      { roomId: "bb-room-1", _count: 3 },
    ]) as never;

    const req = createRequest("/api/blindbox/rooms");
    const res = await GET(req, mockCtx);
    const { status, data } = await parseJsonResponse(res);

    expect(status).toBe(200);
    expect(data.rooms).toHaveLength(1);
    expect(data.rooms[0].code).toBe("ABC123");
    expect(data.rooms[0].poolCount).toBe(3);
  });

  it("returns 401 when not authenticated", async () => {
    vi.mocked(getAuthUserId).mockRejectedValueOnce(new ApiError("请先登录", 401));
    const req = createRequest("/api/blindbox/rooms");
    const res = await GET(req, mockCtx);
    expect(res.status).toBe(401);
  });
});
