/**
 * Rentals API — List and Create
 * GET  /api/dashboard/rentals - List rentals for the user's org
 * POST /api/dashboard/rentals - Create a new rental
 */

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

const log = logger.scope("RentalsAPI");

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

export async function GET(request: NextRequest) {
  try {
    const user = await getAuthenticatedUser(request, auth);
    if (!user) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    const status = request.nextUrl.searchParams.get("status") || undefined;

    const rentals = await convexQuery("vehicles/queries:listRentalsByOrg", {
      organizationId: user.userId,
      status,
    });

    return NextResponse.json({ success: true, rentals: rentals ?? [] });
  } catch (error) {
    log.error("Failed to list rentals", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    if (!validateCSRFToken(request)) {
      return NextResponse.json(
        { success: false, error: "Invalid CSRF token" },
        { status: 403 },
      );
    }

    const user = await getAuthenticatedUser(request, auth);
    if (!user) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    const body = await request.json();
    const {
      vehicleId,
      customerName,
      customerPhone,
      customerEmail,
      customerLicenseNumber,
      pickupDate,
      returnDate,
      durationDays,
      dailyRate,
      totalAmount,
      depositAmount,
      depositPaid,
      depositPaymentId,
      depositPaymentMethod,
      agreementNumber,
      currency,
      notes,
    } = body;

    if (
      !vehicleId ||
      !customerName ||
      !customerPhone ||
      !pickupDate ||
      !returnDate
    ) {
      return NextResponse.json(
        { success: false, error: "Missing required fields" },
        { status: 400 },
      );
    }

    const id = await convexMutation("vehicles/mutations:createRental", {
      organizationId: user.userId,
      userId: user.userId,
      vehicleId,
      customerName,
      customerPhone,
      customerEmail: customerEmail || undefined,
      customerLicenseNumber: customerLicenseNumber || undefined,
      pickupDate: Number(pickupDate),
      returnDate: Number(returnDate),
      durationDays: Number(durationDays),
      dailyRate: Math.round(Number(dailyRate) * 100),
      totalAmount: Math.round(Number(totalAmount) * 100),
      depositAmount: depositAmount
        ? Math.round(Number(depositAmount) * 100)
        : undefined,
      depositPaid: depositPaid ?? false,
      depositPaymentId: depositPaymentId || undefined,
      depositPaymentMethod: depositPaymentMethod || undefined,
      agreementNumber: agreementNumber || undefined,
      currency: currency || "QAR",
      notes: notes || undefined,
    });

    return NextResponse.json({ success: true, id }, { status: 201 });
  } catch (error) {
    log.error("Failed to create rental", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}
