import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireMembership } from "@/lib/blindbox";
import { apiHandler, ApiError, requireUserId } from "@/lib/api";

export const POST = apiHandler(async (req) => {
  const { roomId, userId } = await req.json();

  requireUserId(userId);
  if (!roomId || typeof roomId !== "string") throw new ApiError("roomId 不能为空");

  await requireMembership(roomId, userId);

  const userSelect = { id: true, username: true, avatar: true } as const;

  const idea = await prisma.$transaction(async (tx) => {
    const pool = await tx.blindBoxIdea.findMany({
      where: { roomId, status: "in_pool" },
      select: { id: true },
    });

    if (pool.length === 0) {
      throw new ApiError("盒子是空的，先往里面塞点想法吧！", 404);
    }

    const picked = pool[Math.floor(Math.random() * pool.length)];

    const { count } = await tx.blindBoxIdea.updateMany({
      where: { id: picked.id, status: "in_pool" },
      data: { status: "drawn", drawnById: userId },
    });

    if (count === 0) {
      throw new ApiError("手慢了，再试一次", 409);
    }

    return tx.blindBoxIdea.findUnique({
      where: { id: picked.id },
      include: {
        user: { select: userSelect },
        drawnBy: { select: userSelect },
      },
    });
  });

  if (!idea) throw new ApiError("抽取失败", 500);

  return NextResponse.json({
    id: idea.id,
    content: idea.content,
    createdAt: idea.createdAt,
    submitter: idea.user,
    drawnBy: idea.drawnBy,
  });
});
