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

// DELETE /api/admin/schedules/:id — cancels the whole recurring/one-off schedule
// (all its weekday patterns) and frees up every slot it was holding.
export async function DELETE(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const admin = await getAdminUser();
  if (!admin) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { id } = await params;

  const schedule = await prisma.student_schedules.findUnique({
    where: { id: Number(id) },
    include: { schedule_bookings: { where: { status: "active" } } },
  });

  if (!schedule) return NextResponse.json({ error: "Schedule not found" }, { status: 404 });

  await prisma.$transaction(async (tx) => {
    for (const booking of schedule.schedule_bookings) {
      await tx.time_slots.update({
        where: { id: booking.time_slot_id },
        data: { booked_count: { decrement: 1 } },
      });
      await tx.schedule_bookings.update({
        where: { id: booking.id },
        data: { status: "cancelled" },
      });
    }

    await tx.student_schedules.update({
      where: { id: Number(id) },
      data: { status: "cancelled" },
    });
  });

  return NextResponse.json({ message: "Schedule cancelled" });
}