/**
 * Vehicles API — Single Resource
 * PUT    /api/dashboard/vehicles/[id] - Update a vehicle
 * DELETE /api/dashboard/vehicles/[id] - Soft-delete a 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 { convexMutation } from "@/lib/convex-client";
import { validateCSRFToken } from "@/lib/csrf";

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

export const dynamic = "force-dynamic";

export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> },
) {
  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 { id } = await params;
    const body = await request.json();
    const updates: Record<string, unknown> = {};

    if (body.make !== undefined) updates.make = body.make;
    if (body.model !== undefined) updates.model = body.model;
    if (body.year !== undefined) updates.year = Number(body.year);
    if (body.type !== undefined) updates.type = body.type;
    if (body.color !== undefined) updates.color = body.color;
    if (body.licensePlate !== undefined)
      updates.licensePlate = body.licensePlate;
    if (body.seats !== undefined) updates.seats = Number(body.seats);
    if (body.fuelType !== undefined) updates.fuelType = body.fuelType;
    if (body.transmission !== undefined)
      updates.transmission = body.transmission;
    if (body.pricePerDay !== undefined)
      updates.pricePerDay = Math.round(Number(body.pricePerDay) * 100);
    if (body.pricePerWeek !== undefined)
      updates.pricePerWeek = Math.round(Number(body.pricePerWeek) * 100);
    if (body.pricePerMonth !== undefined)
      updates.pricePerMonth = Math.round(Number(body.pricePerMonth) * 100);
    if (body.depositAmount !== undefined)
      updates.depositAmount = Math.round(Number(body.depositAmount) * 100);
    if (body.descriptionEn !== undefined)
      updates.descriptionEn = body.descriptionEn;
    if (body.isAvailable !== undefined) updates.isAvailable = body.isAvailable;

    await convexMutation("vehicles/mutations:updateVehicle", {
      id,
      ...updates,
    });

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

export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> },
) {
  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 { id } = await params;
    await convexMutation("vehicles/mutations:deleteVehicle", { id });

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