import { prisma } from "@/lib/prisma";
import { ApiError } from "@/lib/api";

export function generateRoomCode(): string {
  const chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
  let code = "";
  for (let i = 0; i < 6; i++) {
    code += chars[Math.floor(Math.random() * chars.length)];
  }
  return code;
}

export async function generateUniqueRoomCode(): Promise<string> {
  for (let attempt = 0; attempt < 10; attempt++) {
    const code = generateRoomCode();
    const existing = await prisma.blindBoxRoom.findUnique({ where: { code } });
    if (!existing) return code;
  }
  throw new Error("无法生成唯一房间号");
}

/** Throws 403 if user is not a member of the room. */
export async function requireMembership(roomId: string, userId: string) {
  const member = await prisma.blindBoxMember.findUnique({
    where: { roomId_userId: { roomId, userId } },
  });
  if (!member) throw new ApiError("你不是这个房间的成员", 403);
  return member;
}

export async function getRoomByCode(code: string) {
  return prisma.blindBoxRoom.findUnique({
    where: { code },
    include: {
      members: {
        include: { user: { select: { id: true, username: true, avatar: true } } },
      },
      _count: { select: { ideas: { where: { status: "in_pool" } } } },
    },
  });
}
