/**
 * Rentals API — Single Resource
 * PUT /api/dashboard/rentals/[id] - Update rental status
 */

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

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 { status, actualReturnDate, mileageAtReturn, damageNotes } =
      await request.json();

    if (!status) {
      return NextResponse.json(
        { success: false, error: "status is required" },
        { status: 400 },
      );
    }

    await convexMutation("vehicles/mutations:updateRentalStatus", {
      id,
      status,
      actualReturnDate: actualReturnDate ? Number(actualReturnDate) : undefined,
      mileageAtReturn: mileageAtReturn ? Number(mileageAtReturn) : undefined,
      damageNotes: damageNotes || undefined,
    });

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