import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { getAdminUser } from "@/lib/auth";

export async function GET(req: NextRequest) {
  const admin = await getAdminUser();
  if (!admin) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const startDate = req.nextUrl.searchParams.get("start_date");
  const endDate = req.nextUrl.searchParams.get("end_date");

  if (!startDate || !endDate) {
    return NextResponse.json({ error: "start_date and end_date are required" }, { status: 400 });
  }

  const slots = await prisma.time_slots.findMany({
    where: { slot_date: { gte: new Date(startDate), lte: new Date(endDate) } },
    orderBy: [{ slot_date: "asc" }, { start_time: "asc" }],
  });

  // Group by weekday, then by unique start_time-end_time, aggregating booked/capacity
  const byWeekday: Record<number, Record<string, { start_time: string; end_time: string; capacity: number; booked_count: number }>> = {};

  for (const slot of slots) {
    const weekday = slot.slot_date.getDay();
    const key = `${slot.start_time}-${slot.end_time}`;
    if (!byWeekday[weekday]) byWeekday[weekday] = {};
    if (!byWeekday[weekday][key]) {
      byWeekday[weekday][key] = {
        start_time: slot.start_time,
        end_time: slot.end_time,
        capacity: slot.capacity,
        booked_count: 0,
      };
    }
    byWeekday[weekday][key].booked_count += slot.booked_count;
  }

  const result = Object.entries(byWeekday).map(([weekday, times]) => ({
    weekday: Number(weekday),
    slots: Object.values(times),
  }));

  return NextResponse.json({ data: result });
}