import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { getAdminUser } from "@/lib/auth";
import { toMinutes, toHHMM, parseDateUTC } from "@/lib/timeslot-utils";
import { SLOT_DURATION_MINUTES, DEFAULT_SLOT_CAPACITY } from "@/lib/timeslot-constants";

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

  const date = req.nextUrl.searchParams.get("date");
  if (!date) return NextResponse.json({ error: "date query param is required" }, { status: 400 });

  const slots = await prisma.time_slots.findMany({
    where: { slot_date: parseDateUTC(date) },
    orderBy: { start_time: "asc" },
  });

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

// POST: add a one-off slot for a specific date.
// Only start_time is accepted — end_time/capacity are always derived from the static constants.
export async function POST(req: NextRequest) {
  const admin = await getAdminUser();
  if (!admin) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const body = await req.json();
  const { slot_date, start_time } = body;

  if (!slot_date || !start_time) {
    return NextResponse.json({ error: "slot_date and start_time are required" }, { status: 400 });
  }

  const newStartMins = toMinutes(start_time);
  const newEndMins = newStartMins + SLOT_DURATION_MINUTES;
  const end_time = toHHMM(newEndMins);
  const parsedDate = parseDateUTC(slot_date);

  // Server-side overlap check — authoritative, since the client-side check
  // can't see slots created by another admin between page load and submit
  const existingSlots = await prisma.time_slots.findMany({ where: { slot_date: parsedDate } });

  const overlaps = existingSlots.some((s) => {
    const existingStart = toMinutes(s.start_time);
    const existingEnd = toMinutes(s.end_time);
    return newStartMins < existingEnd && newEndMins > existingStart;
  });

  if (overlaps) {
    return NextResponse.json(
      { error: "This time overlaps with an existing slot on this date." },
      { status: 409 }
    );
  }

  const slot = await prisma.time_slots.create({
    data: {
      slot_date: parsedDate,
      start_time,
      end_time,
      capacity: DEFAULT_SLOT_CAPACITY,
      is_override: true,
    },
  });

  return NextResponse.json({ data: slot }, { status: 201 });
}