import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireRole } from "@/lib/auth";
import { VEHICLE_TYPES } from "@/lib/constants";

type Params = { params: Promise<{ id: string }> };

/** Update a vehicle. */
export async function PUT(req: Request, { params }: Params) {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const { id } = await params;

  try {
    const body = await req.json();
    const vehicle = await prisma.transportVehicle.findFirst({
      where: { id: Number(id), institutionId: session.institutionId },
    });
    if (!vehicle) return NextResponse.json({ error: "Not found" }, { status: 404 });

    const name = String(body.name ?? vehicle.name).trim();
    if (!name) return NextResponse.json({ error: "Name required" }, { status: 400 });

    await prisma.transportVehicle.update({
      where: { id: vehicle.id },
      data: {
        name,
        registrationNo: body.registrationNo !== undefined ? String(body.registrationNo).trim() || null : vehicle.registrationNo,
        type: VEHICLE_TYPES.includes(body.type as never) ? body.type : vehicle.type,
        capacity: body.capacity !== undefined ? Math.max(0, Number(body.capacity) || 0) : vehicle.capacity,
        driverName: body.driverName !== undefined ? String(body.driverName).trim() || null : vehicle.driverName,
        driverPhone: body.driverPhone !== undefined ? String(body.driverPhone).trim() || null : vehicle.driverPhone,
        status: body.status === "INACTIVE" ? "INACTIVE" : body.status === "ACTIVE" ? "ACTIVE" : vehicle.status,
      },
    });
    return NextResponse.json({ success: true });
  } catch {
    return NextResponse.json({ error: "Could not update vehicle" }, { status: 500 });
  }
}

/** Delete a vehicle (only when no route is assigned to it). */
export async function DELETE(_req: Request, { params }: Params) {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const { id } = await params;

  const vehicle = await prisma.transportVehicle.findFirst({
    where: { id: Number(id), institutionId: session.institutionId },
  });
  if (!vehicle) return NextResponse.json({ error: "Not found" }, { status: 404 });

  const routes = await prisma.transportRoute.count({ where: { vehicleId: vehicle.id } });
  if (routes > 0) return NextResponse.json({ error: "IN_USE" }, { status: 409 });

  await prisma.transportVehicle.delete({ where: { id: vehicle.id } });
  return NextResponse.json({ success: true });
}
