/**
 * Vehicles API — List and Create
 * GET  /api/dashboard/vehicles - List vehicles for the user's org
 * POST /api/dashboard/vehicles - Create a new vehicle
 */

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("VehiclesAPI");

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 includeInactive =
      request.nextUrl.searchParams.get("includeInactive") === "true";

    const vehicles = await convexQuery("vehicles/queries:listByOrg", {
      organizationId: user.userId,
      includeInactive,
    });

    return NextResponse.json({ success: true, vehicles: vehicles ?? [] });
  } catch (error) {
    log.error("Failed to list vehicles", 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 {
      make,
      model,
      year,
      type,
      color,
      licensePlate,
      seats,
      fuelType,
      transmission,
      pricePerDay,
      pricePerWeek,
      pricePerMonth,
      currency,
      depositAmount,
      descriptionEn,
    } = body;

    if (!make || !model || !year || !type || !pricePerDay || !currency) {
      return NextResponse.json(
        { success: false, error: "Missing required fields" },
        { status: 400 },
      );
    }

    const id = await convexMutation("vehicles/mutations:createVehicle", {
      organizationId: user.userId,
      userId: user.userId,
      make,
      model,
      year: Number(year),
      type,
      color: color || undefined,
      licensePlate: licensePlate || undefined,
      seats: seats ? Number(seats) : undefined,
      fuelType: fuelType || undefined,
      transmission: transmission || undefined,
      pricePerDay: Math.round(Number(pricePerDay) * 100),
      pricePerWeek: pricePerWeek
        ? Math.round(Number(pricePerWeek) * 100)
        : undefined,
      pricePerMonth: pricePerMonth
        ? Math.round(Number(pricePerMonth) * 100)
        : undefined,
      currency,
      depositAmount: depositAmount
        ? Math.round(Number(depositAmount) * 100)
        : undefined,
      descriptionEn: descriptionEn || undefined,
    });

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