/**
 * Vehicle Bulk Import API
 *
 * POST /api/dashboard/vehicles/import
 *   Accepts a pre-parsed array of vehicle objects (frontend parses CSV).
 *
 * Request body:
 *   { vehicles: Array<{ make, model, year, type, pricePerDay, ... }> }
 *
 * Response:
 *   { success: true, imported: number, errors: string[] }
 */

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 { convexMutation } from "@/lib/convex-client";
import { withCSRF } from "@/lib/csrf";
import { withRateLimit, rateLimiters } from "@/lib/rate-limiter";
import type {
  VehicleType,
  FuelType,
  Transmission,
} from "@/lib/types/vehicles.types";

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

export const dynamic = "force-dynamic";

const MAX_IMPORT = 100;

const VALID_VEHICLE_TYPES: VehicleType[] = [
  "CAR",
  "SUV",
  "VAN",
  "TRUCK",
  "MOTORCYCLE",
  "BUS",
  "LUXURY",
  "ELECTRIC",
];
const VALID_FUEL_TYPES: FuelType[] = ["PETROL", "DIESEL", "ELECTRIC", "HYBRID"];
const VALID_TRANSMISSIONS: Transmission[] = ["AUTOMATIC", "MANUAL"];

interface ImportVehicleRow {
  make?: string;
  model?: string;
  year?: number | string;
  type?: string;
  color?: string;
  licensePlate?: string;
  seats?: number | string;
  fuelType?: string;
  transmission?: string;
  pricePerDay?: number | string;
  pricePerWeek?: number | string;
  pricePerMonth?: number | string;
  depositAmount?: number | string;
  descriptionEn?: string;
}

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

    let body: unknown;
    try {
      body = await request.json();
    } catch {
      return NextResponse.json(
        { success: false, error: "Invalid JSON body" },
        { status: 400 },
      );
    }

    const { vehicles } = body as { vehicles?: unknown[] };

    if (!Array.isArray(vehicles) || vehicles.length === 0) {
      return NextResponse.json(
        { success: false, error: "vehicles must be a non-empty array" },
        { status: 400 },
      );
    }

    if (vehicles.length > MAX_IMPORT) {
      return NextResponse.json(
        {
          success: false,
          error: `Cannot import more than ${MAX_IMPORT} vehicles at once`,
        },
        { status: 400 },
      );
    }

    const errors: string[] = [];
    let imported = 0;

    for (let i = 0; i < vehicles.length; i++) {
      const row = vehicles[i] as ImportVehicleRow;
      const rowLabel = `Row ${i + 1}`;

      // Validate required fields
      const make = row.make ? String(row.make).trim() : "";
      const model = row.model ? String(row.model).trim() : "";
      if (!make) {
        errors.push(`${rowLabel}: make is required`);
        continue;
      }
      if (!model) {
        errors.push(`${rowLabel}: model is required`);
        continue;
      }

      const year = Number(row.year);
      if (!row.year || isNaN(year) || year < 1990 || year > 2030) {
        errors.push(`${rowLabel}: year must be between 1990 and 2030`);
        continue;
      }

      const vehicleType = row.type
        ? String(row.type).trim().toUpperCase()
        : "CAR";
      if (!VALID_VEHICLE_TYPES.includes(vehicleType as VehicleType)) {
        errors.push(
          `${rowLabel}: invalid type "${row.type}". Valid: ${VALID_VEHICLE_TYPES.join(", ")}`,
        );
        continue;
      }

      const pricePerDay = Number(row.pricePerDay);
      if (!row.pricePerDay || isNaN(pricePerDay) || pricePerDay <= 0) {
        errors.push(`${rowLabel}: pricePerDay must be a positive number`);
        continue;
      }

      // Validate optional fields
      let fuelType: string | undefined;
      if (row.fuelType) {
        const ft = String(row.fuelType).trim().toUpperCase();
        if (!VALID_FUEL_TYPES.includes(ft as FuelType)) {
          errors.push(
            `${rowLabel}: invalid fuelType "${row.fuelType}". Valid: ${VALID_FUEL_TYPES.join(", ")}`,
          );
          continue;
        }
        fuelType = ft;
      }

      let transmission: string | undefined;
      if (row.transmission) {
        const tr = String(row.transmission).trim().toUpperCase();
        if (!VALID_TRANSMISSIONS.includes(tr as Transmission)) {
          errors.push(
            `${rowLabel}: invalid transmission "${row.transmission}". Valid: ${VALID_TRANSMISSIONS.join(", ")}`,
          );
          continue;
        }
        transmission = tr;
      }

      const seats = row.seats ? Number(row.seats) : undefined;
      if (seats !== undefined && (isNaN(seats) || seats < 1 || seats > 100)) {
        errors.push(`${rowLabel}: seats must be between 1 and 100`);
        continue;
      }

      const pricePerWeek = row.pricePerWeek
        ? Number(row.pricePerWeek)
        : undefined;
      if (
        pricePerWeek !== undefined &&
        (isNaN(pricePerWeek) || pricePerWeek < 0)
      ) {
        errors.push(`${rowLabel}: pricePerWeek must be non-negative`);
        continue;
      }

      const pricePerMonth = row.pricePerMonth
        ? Number(row.pricePerMonth)
        : undefined;
      if (
        pricePerMonth !== undefined &&
        (isNaN(pricePerMonth) || pricePerMonth < 0)
      ) {
        errors.push(`${rowLabel}: pricePerMonth must be non-negative`);
        continue;
      }

      const depositAmount = row.depositAmount
        ? Number(row.depositAmount)
        : undefined;
      if (
        depositAmount !== undefined &&
        (isNaN(depositAmount) || depositAmount < 0)
      ) {
        errors.push(`${rowLabel}: depositAmount must be non-negative`);
        continue;
      }

      // Create vehicle via Convex mutation (one at a time since Convex doesn't have createMany)
      try {
        await convexMutation("vehicles/mutations:createVehicle", {
          organizationId: user.userId,
          userId: user.userId,
          make,
          model,
          year,
          type: vehicleType,
          color: row.color ? String(row.color).trim() : undefined,
          licensePlate: row.licensePlate
            ? String(row.licensePlate).trim()
            : undefined,
          seats,
          fuelType,
          transmission,
          pricePerDay: Math.round(pricePerDay * 100),
          pricePerWeek:
            pricePerWeek !== undefined
              ? Math.round(pricePerWeek * 100)
              : undefined,
          pricePerMonth:
            pricePerMonth !== undefined
              ? Math.round(pricePerMonth * 100)
              : undefined,
          currency: "QAR",
          depositAmount:
            depositAmount !== undefined
              ? Math.round(depositAmount * 100)
              : undefined,
          descriptionEn: row.descriptionEn
            ? String(row.descriptionEn).trim()
            : undefined,
        });
        imported++;
      } catch (err) {
        errors.push(
          `${rowLabel}: failed to create - ${err instanceof Error ? err.message : "unknown error"}`,
        );
      }
    }

    log.info("Vehicle bulk import completed", {
      userId: user.userId,
      requested: vehicles.length,
      imported,
      errorCount: errors.length,
    });

    return NextResponse.json({ success: true, imported, errors });
  } catch (error) {
    log.error("Failed to bulk import vehicles", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}

export const POST = withRateLimit(
  withCSRF(postHandler),
  rateLimiters.authGeneral,
);
