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

interface StopInput {
  name?: string;
  nameBn?: string;
  extraFare?: number | string;
}

/** Create a route with its stops: { name, nameBn?, vehicleId?, baseFare, stops: [{ name, extraFare }] }. */
export async function POST(req: Request) {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const body = await req.json();
    const name = String(body.name ?? "").trim();
    if (!name) return NextResponse.json({ error: "Missing fields" }, { status: 400 });

    const stopsIn: StopInput[] = Array.isArray(body.stops) ? body.stops : [];
    const stops = stopsIn
      .map((s, i) => ({
        institutionId: session.institutionId!,
        name: String(s.name ?? "").trim(),
        nameBn: String(s.nameBn ?? "").trim() || null,
        extraFare: Math.max(0, Number(s.extraFare) || 0),
        sortOrder: i,
      }))
      .filter((s) => s.name);

    let vehicleId: number | null = null;
    if (body.vehicleId) {
      const vehicle = await prisma.transportVehicle.findFirst({
        where: { id: Number(body.vehicleId), institutionId: session.institutionId },
      });
      if (!vehicle) return NextResponse.json({ error: "Vehicle not found" }, { status: 404 });
      vehicleId = vehicle.id;
    }

    const route = await prisma.transportRoute.create({
      data: {
        institutionId: session.institutionId,
        name,
        nameBn: String(body.nameBn ?? "").trim() || null,
        vehicleId,
        baseFare: Math.max(0, Number(body.baseFare) || 0),
        isActive: true,
        stops: { create: stops },
      },
      include: { stops: true },
    });
    return NextResponse.json({ route });
  } catch {
    return NextResponse.json({ error: "Could not create route" }, { status: 500 });
  }
}
