/**
 * Fetch Demo Bookings Endpoint
 *
 * Supports two modes:
 * 1. ?date=YYYY-MM-DD - Returns bookings for specific date (for duplicate prevention)
 * 2. ?all=true - Returns all demo bookings (for dashboard)
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { convexQuery } from "@/lib/convex-client";
import { demoBookingsQuerySchema } from "@/lib/validators/api-schemas";

export const dynamic = "force-dynamic";
export const runtime = "nodejs";

/**
 * GET /api/demo/bookings?date=YYYY-MM-DD
 * GET /api/demo/bookings?all=true
 * GET /api/demo/bookings?all=true&limit=50
 * GET /api/demo/bookings?all=true&status=pending
 */
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const queryParams: Record<string, string> = {};
    searchParams.forEach((value, key) => { queryParams[key] = value; });
    const parsed = demoBookingsQuerySchema.safeParse(queryParams);

    if (!parsed.success) {
      return NextResponse.json(
        { error: parsed.error.errors.map(e => `${e.path.join(".")}: ${e.message}`).join(", ") },
        { status: 400 },
      );
    }

    const { date, all, limit, status } = parsed.data;

    // Mode 1: Fetch all bookings (requires authentication)
    if (all === "true") {
      // Check authentication for dashboard access
      const session = await auth();
      if (!session?.user?.id) {
        return NextResponse.json(
          { error: "Authentication required" },
          { status: 401 },
        );
      }

      const convexBookings = await convexQuery(
        "bookings/queries:getDemoBookings",
        {
          status: status ?? undefined,
          limit,
        },
      );
      const bookings = (convexBookings as Array<Record<string, unknown>>) ?? [];
      return NextResponse.json({
        success: true,
        bookings,
        count: bookings.length,
      });
    }

    // Mode 2: Fetch bookings for specific date (public - for duplicate prevention)
    if (!date) {
      return NextResponse.json(
        { error: "Date parameter is required (or use ?all=true)" },
        { status: 400 },
      );
    }

    // Create start and end of day for date range query
    const startOfDay = new Date(`${date}T00:00:00.000Z`);
    const endOfDay = new Date(`${date}T23:59:59.999Z`);

    const convexBookings = await convexQuery(
      "bookings/queries:getDemoBookingsByDate",
      {
        startDate: startOfDay.getTime(),
        endDate: endOfDay.getTime(),
      },
    );
    const takenSlots = (
      (convexBookings as Array<Record<string, unknown>>) ?? []
    ).map((b) => ({ time: b.appointmentTime, duration: b.duration }));
    return NextResponse.json({
      success: true,
      date,
      takenSlots,
      count: takenSlots.length,
    });
  } catch (error) {
    console.error("Bookings API error:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 },
    );
  }
}
