// app/api/student/schedule/slots/route.ts
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { parseDateUTC } from "@/lib/timeslot-utils";
import { getStudent } from "@/lib/studentAuth";

export async function GET(req: NextRequest) {
  const student = await getStudent();
  if (!student) 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: parseDateUTC(startDate), lte: parseDateUTC(endDate) },
      active_status: true,
    },
    orderBy: [{ slot_date: "asc" }, { start_time: "asc" }],
  });

  const byDate: Record<string, { id: number; start_time: string; end_time: string; capacity: number; booked_count: number }[]> = {};
  for (const s of slots) {
    const key = s.slot_date.toISOString().slice(0, 10);
    if (!byDate[key]) byDate[key] = [];
    byDate[key].push({
      id: s.id,
      start_time: s.start_time,
      end_time: s.end_time,
      capacity: s.capacity,
      booked_count: s.booked_count,
    });
  }

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