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_ROOM } from "@/__tests__/helpers/fixtures";

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

import { POST } from "./route";

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

beforeEach(() => {
  resetPrismaMock();
});

describe("POST /api/blindbox/room/join", () => {
  it("joins a room by code", async () => {
    prismaMock.blindBoxRoom.findUnique.mockResolvedValue(TEST_BLINDBOX_ROOM as never);
    prismaMock.blindBoxMember.findUnique.mockResolvedValue(null as never);
    prismaMock.blindBoxMember.create.mockResolvedValue({} as never);

    const req = createRequest("/api/blindbox/room/join", {
      method: "POST",
      body: { code: "ABC123" },
    });
    const res = await POST(req, mockCtx);
    const { status, data } = await parseJsonResponse(res);

    expect(status).toBe(201);
    expect(data.code).toBe("ABC123");
  });

  it("returns alreadyMember if already joined", async () => {
    prismaMock.blindBoxRoom.findUnique.mockResolvedValue(TEST_BLINDBOX_ROOM as never);
    prismaMock.blindBoxMember.findUnique.mockResolvedValue({ id: "member-1" } as never);

    const req = createRequest("/api/blindbox/room/join", {
      method: "POST",
      body: { code: "ABC123" },
    });
    const res = await POST(req, mockCtx);
    const { data } = await parseJsonResponse(res);

    expect(data.alreadyMember).toBe(true);
  });

  it("returns 404 when room code not found", async () => {
    prismaMock.blindBoxRoom.findUnique.mockResolvedValue(null as never);

    const req = createRequest("/api/blindbox/room/join", {
      method: "POST",
      body: { code: "BADCODE" },
    });
    const res = await POST(req, mockCtx);
    expect(res.status).toBe(404);
  });

  it("returns 400 when code is missing", async () => {
    const req = createRequest("/api/blindbox/room/join", {
      method: "POST",
      body: {},
    });
    const res = await POST(req, mockCtx);
    expect(res.status).toBe(400);
  });
});
