// import { NextRequest, NextResponse } from "next/server";
// import { prisma } from "@/lib/prisma";
// import { getAdminUser } from "@/lib/auth";
// 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 masters = await prisma.master_time_slots.findMany({
//     where: { delete_status: false },
//     include: {
//       master_time_slot_days: {
//         include: { master_time_slot_sessions: true },
//         orderBy: { weekday: "asc" },
//       },
//     },
//     orderBy: { created_at: "desc" },
//   });

//   return NextResponse.json({ data: masters });
// }

// interface SessionInput { start_time: string; end_time: string; } // duration/capacity removed — static now
// interface DayInput { weekday: number; is_closed: boolean; sessions: SessionInput[]; }
// interface CreateMasterBody { start_date: string; end_date: string; days: DayInput[]; }

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

//   const body: CreateMasterBody = await req.json();

//   if (!body.start_date || !body.end_date || !body.days?.length) {
//     return NextResponse.json({ error: "start_date, end_date and days are required" }, { status: 400 });
//   }

//   const master = await prisma.master_time_slots.create({
//     data: {
//       start_date: new Date(body.start_date),
//       end_date: new Date(body.end_date),
//       master_time_slot_days: {
//         create: body.days.map((day) => ({
//           weekday: day.weekday,
//           is_closed: day.is_closed,
//           master_time_slot_sessions: {
//             create: day.is_closed
//               ? []
//               : day.sessions.map((s) => ({
//                   start_time: s.start_time,
//                   end_time: s.end_time,
//                   duration_mins: SLOT_DURATION_MINUTES, // static, ignores any client input
//                   capacity: DEFAULT_SLOT_CAPACITY,       // static, ignores any client input
//                 })),
//           },
//         })),
//       },
//     },
//     include: { master_time_slot_days: { include: { master_time_slot_sessions: true } } },
//   });

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

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

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

  const masters = await prisma.master_time_slots.findMany({
    where: { delete_status: false },
    include: {
      master_time_slot_days: {
        include: { master_time_slot_sessions: true },
        orderBy: { weekday: "asc" },
      },
    },
    orderBy: { created_at: "desc" },
  });

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

interface SessionInput { start_time: string; end_time: string; }
interface DayInput { weekday: number; is_closed: boolean; sessions: SessionInput[]; }
interface CreateMasterBody { start_date: string; end_date: string; days: DayInput[]; }

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

  const body: CreateMasterBody = await req.json();

  if (!body.start_date || !body.end_date || !body.days?.length) {
    return NextResponse.json({ error: "start_date, end_date and days are required" }, { status: 400 });
  }

  // parseDateUTC instead of new Date(body.start_date) — prevents the same
  // local-timezone drift from affecting the overlap check and stored range
  const newStart = parseDateUTC(body.start_date);
  const newEnd = parseDateUTC(body.end_date);

  if (newEnd < newStart) {
    return NextResponse.json({ error: "End date must be after start date" }, { status: 400 });
  }

  const overlapping = await prisma.master_time_slots.findFirst({
    where: {
      delete_status: false,
      start_date: { lte: newEnd },
      end_date: { gte: newStart },
    },
  });

  if (overlapping) {
    return NextResponse.json(
      {
        error: `This date range overlaps with an existing master (${overlapping.start_date
          .toISOString()
          .slice(0, 10)} to ${overlapping.end_date.toISOString().slice(0, 10)}). Choose a non-overlapping range or edit that master instead.`,
      },
      { status: 409 }
    );
  }

  const master = await prisma.master_time_slots.create({
    data: {
      start_date: newStart,
      end_date: newEnd,
      master_time_slot_days: {
        create: body.days.map((day) => ({
          weekday: day.weekday,
          is_closed: day.is_closed,
          master_time_slot_sessions: {
            create: day.is_closed
              ? []
              : day.sessions.map((s) => ({
                  start_time: s.start_time,
                  end_time: s.end_time,
                  duration_mins: SLOT_DURATION_MINUTES,
                  capacity: DEFAULT_SLOT_CAPACITY,
                })),
          },
        })),
      },
    },
    include: { master_time_slot_days: { include: { master_time_slot_sessions: true } } },
  });

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