import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { getAdminUser } from "@/lib/auth";
import { chunkTimeRange, getDatesInRange, formatDateUTC } from "@/lib/timeslot-utils";
import { SLOT_DURATION_MINUTES, DEFAULT_SLOT_CAPACITY } from "@/lib/timeslot-constants";

export async function POST(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 master = await prisma.master_time_slots.findUnique({
    where: { id: Number(id) },
    include: { master_time_slot_days: { include: { master_time_slot_sessions: true } } },
  });

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

  // formatDateUTC replaces the old .toISOString().slice(0,10) call on the raw
  // Prisma Date — same output here, but kept consistent with the new util naming
  const dates = getDatesInRange(formatDateUTC(master.start_date), formatDateUTC(master.end_date));

  let createdCount = 0;
  let skippedOverrideCount = 0;

  for (const date of dates) {
    // getUTCDay() instead of getDay() — getDay() reads the LOCAL weekday, which
    // for a UTC-midnight date can report the wrong day in timezones like +5:30
    const weekday = date.getUTCDay();
    const dayConfig = master.master_time_slot_days.find((d) => d.weekday === weekday);
    if (!dayConfig || dayConfig.is_closed) continue;

    for (const session of dayConfig.master_time_slot_sessions) {
      const chunks = chunkTimeRange(session.start_time, session.end_time, SLOT_DURATION_MINUTES);

      for (const chunk of chunks) {
        const existing = await prisma.time_slots.findUnique({
          where: {
            slot_date_start_time_end_time: {
              slot_date: date,
              start_time: chunk.start,
              end_time: chunk.end,
            },
          },
        });

        if (existing?.is_override) {
          skippedOverrideCount++;
          continue;
        }

        await prisma.time_slots.upsert({
          where: {
            slot_date_start_time_end_time: {
              slot_date: date,
              start_time: chunk.start,
              end_time: chunk.end,
            },
          },
          update: { capacity: DEFAULT_SLOT_CAPACITY, master_session_id: session.id },
          create: {
            slot_date: date,
            start_time: chunk.start,
            end_time: chunk.end,
            capacity: DEFAULT_SLOT_CAPACITY,
            master_session_id: session.id,
          },
        });
        createdCount++;
      }
    }
  }

  return NextResponse.json({
    message: `Generated ${createdCount} slots. ${skippedOverrideCount} manually-edited dates were left unchanged.`,
  });
}