/**
 * Bookings API
 * GET - Returns appointment bookings for the dashboard
 * POST - Creates a new booking/appointment
 *
 * All data access goes through Convex. No Prisma fallback.
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { getAuthenticatedEmail } from "@/lib/utils/auth-helpers.util";
import { logger } from "@/lib/logger";
import { validateCSRFToken } from "@/lib/csrf";
import { convexQuery, convexMutation } from "@/lib/convex-client";
import { createBookingSchema } from "@/lib/validators/api-schemas";

export const dynamic = "force-dynamic";

interface ConvexUser {
  _id: string;
  prismaId?: string;
  appUserId?: string;
  email: string;
}

/**
 * GET /api/bookings
 * Returns all bookings for the authenticated user
 */
export async function GET(request: NextRequest) {
  try {
    const userEmail = await getAuthenticatedEmail(request, auth);

    if (!userEmail) {
      logger.warn("Unauthorized bookings request");
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    // Get user from Convex
    const convexUser = await convexQuery<ConvexUser>(
      "auth/queries:getUserByEmail",
      { email: userEmail },
    );

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

    const userId =
      convexUser.prismaId || convexUser.appUserId || convexUser._id;

    const searchParams = request.nextUrl.searchParams;
    const status = searchParams.get("status") ?? undefined;
    const limit = searchParams.get("limit")
      ? parseInt(searchParams.get("limit")!)
      : 50;

    const bookings = await convexQuery("bookings/queries:getBookings", {
      userId,
      ...(status && status !== "all" ? { status } : {}),
      ...(limit ? { limit } : {}),
    });

    if (bookings) {
      return NextResponse.json({
        success: true,
        bookings,
        total: Array.isArray(bookings) ? bookings.length : 0,
        limit,
      });
    }

    // Convex returned null — return empty
    return NextResponse.json({
      success: true,
      bookings: [],
      total: 0,
      limit,
    });
  } catch (error) {
    logger.error("Bookings error", {
      error: error instanceof Error ? error.message : "Unknown error",
    });

    return NextResponse.json(
      { error: "Failed to retrieve bookings" },
      { status: 500 },
    );
  }
}

/**
 * POST /api/bookings
 * Creates a new booking/appointment
 */
export async function POST(request: NextRequest) {
  try {
    const userEmail = await getAuthenticatedEmail(request, auth);

    if (!userEmail) {
      logger.warn("Unauthorized booking creation attempt");
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    // CSRF protection (bypass in development for easier testing)
    if (process.env.NODE_ENV !== "development") {
      const isValidCSRF = validateCSRFToken(request);
      if (!isValidCSRF) {
        return NextResponse.json(
          { success: false, error: "Invalid CSRF token" },
          { status: 403 },
        );
      }
    }

    // Get user from Convex
    const convexUser = await convexQuery<ConvexUser>(
      "auth/queries:getUserByEmail",
      { email: userEmail },
    );

    if (!convexUser) {
      return NextResponse.json(
        { success: false, error: "User not found" },
        { status: 404 },
      );
    }

    const userId =
      convexUser.prismaId || convexUser.appUserId || convexUser._id;

    // Parse and validate request body
    const body = await request.json();
    const parsed = createBookingSchema.safeParse(body);

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

    const data = parsed.data;
    const appointmentDateValue =
      data.appointmentDate instanceof Date
        ? data.appointmentDate.getTime()
        : new Date(String(data.appointmentDate)).getTime();

    // Extract optional sector fields from body (not in Zod schema)
    const sectorMetadata =
      body.sectorMetadata && typeof body.sectorMetadata === "object"
        ? (body.sectorMetadata as Record<string, unknown>)
        : undefined;
    const itemType =
      typeof body.itemType === "string" ? body.itemType : undefined;

    const mutationArgs: Record<string, unknown> = {
      userId,
      customerName: data.customerName,
      customerPhone: data.customerPhone,
      customerEmail: data.customerEmail ?? "",
      service: data.service,
      appointmentDate: appointmentDateValue,
      appointmentTime: data.appointmentTime,
      duration: data.duration,
      staffMember: data.staffMember,
      totalAmount: data.totalAmount,
      source: body.source ?? "manual",
      notes: data.notes,
    };

    if (sectorMetadata) {
      mutationArgs.sectorMetadata = sectorMetadata;
    }
    if (itemType) {
      mutationArgs.itemType = itemType;
    }

    const booking = await convexMutation(
      "bookings/mutations:create",
      mutationArgs,
    );
    return NextResponse.json({ booking }, { status: 201 });
  } catch (error) {
    logger.error("Failed to create booking", {
      error: error instanceof Error ? error.message : "Unknown error",
    });

    return NextResponse.json(
      { success: false, error: "Failed to create booking" },
      { status: 500 },
    );
  }
}
