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

export const GET = apiHandler(async (req) => {
  const userId = requireUserId(req.nextUrl.searchParams.get("userId"));

  const memberships = await prisma.blindBoxMember.findMany({
    where: { userId },
    include: {
      room: {
        include: {
          members: {
            include: { user: { select: { id: true, username: true, avatar: true } } },
            orderBy: { joinedAt: "asc" },
            take: 5,
          },
          _count: {
            select: { ideas: true, members: true },
          },
          ideas: {
            where: { status: "drawn" },
            orderBy: { createdAt: "desc" },
            take: 1,
            select: { content: true, createdAt: true },
          },
        },
      },
    },
    orderBy: { joinedAt: "desc" },
  });

  const rooms = memberships.map((m) => ({
    id: m.room.id,
    code: m.room.code,
    name: m.room.name,
    memberCount: m.room._count.members,
    ideaCount: m.room._count.ideas,
    poolCount: 0,
    members: m.room.members.map((mb) => mb.user),
    lastDrawn: m.room.ideas[0] ?? null,
    joinedAt: m.joinedAt,
  }));

  const roomIds = rooms.map((r) => r.id);
  const poolCounts = await prisma.blindBoxIdea.groupBy({
    by: ["roomId"],
    where: { roomId: { in: roomIds }, status: "in_pool" },
    _count: true,
  });
  const poolMap = new Map(poolCounts.map((p) => [p.roomId, p._count]));

  for (const room of rooms) {
    room.poolCount = poolMap.get(room.id) ?? 0;
  }

  return NextResponse.json({ rooms });
});
