import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { parseDateUTC, fmt12 } from "@/lib/timeslot-utils";
import { getStudent } from "@/lib/studentAuth";

export async function GET() {
    const auth: any = await getStudent();
    if (!auth) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

    const studentId = auth.id;
    const todayKey = new Date().toISOString().slice(0, 10);
    const today = parseDateUTC(todayKey);

    // Pull every active booking for this student, across all their active
    // schedules, ordered chronologically. We split it into today/upcoming/past
    // in JS below rather than three separate queries, since it's the same
    // underlying rowset and this avoids hitting the DB three times.
    const schedules = await prisma.student_schedules.findMany({
        where: { student_id: studentId, status: "active" },
        include: {
            schedule_bookings: {
                where: { status: "active" },
                include: { time_slots: { select: { start_time: true, end_time: true } } },
                orderBy: { booking_date: "asc" },
            },
        },
    });

    const allBookings = schedules.flatMap((s) =>
        s.schedule_bookings.map((b) => ({
            id: b.id,
            booking_date: b.booking_date.toISOString().slice(0, 10),
            start_time: b.time_slots.start_time,
            end_time: b.time_slots.end_time,
            schedule_id: s.id,
        }))
    );

    const todaysClasses = allBookings.filter((b) => b.booking_date === todayKey);

    const allUpcoming = allBookings
        .filter((b) => b.booking_date > todayKey)
        .sort((a, b) => (a.booking_date === b.booking_date ? a.start_time.localeCompare(b.start_time) : a.booking_date.localeCompare(b.booking_date)));

    const upcomingClasses = allUpcoming.slice(0, 5); // still capped for the dashboard preview list
    const pastClasses = allBookings.filter((b) => b.booking_date < todayKey);

    const pendingRequestsCount = await prisma.schedule_change_requests.count({
        where: { student_id: studentId, status: "pending" },
    });

    const nextClass = todaysClasses.sort((a, b) => a.start_time.localeCompare(b.start_time))[0] ?? allUpcoming[0] ?? null;

    return NextResponse.json({
        data: {
            todaysClasses,
            upcomingClasses,
            nextClass,
            stats: {
                totalScheduled: allBookings.length,
                upcomingCount: allUpcoming.length + todaysClasses.length, // use the FULL list, not the sliced one
                completedCount: pastClasses.length,
                pendingRequestsCount,
            },
        },
    });
}