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

/** Assign a student to a route/stop: { studentId, routeId, stopId?, monthlyFare? }. */
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 studentId = Number(body.studentId);
    const routeId = Number(body.routeId);
    if (!studentId || !routeId) {
      return NextResponse.json({ error: "Missing fields" }, { status: 400 });
    }

    const [student, route] = await Promise.all([
      prisma.student.findFirst({
        where: { id: studentId, institutionId: session.institutionId, status: "ACTIVE" },
      }),
      prisma.transportRoute.findFirst({
        where: { id: routeId, institutionId: session.institutionId },
        include: { stops: true },
      }),
    ]);
    if (!student) return NextResponse.json({ error: "Student not found" }, { status: 404 });
    if (!route) return NextResponse.json({ error: "Route not found" }, { status: 404 });

    let stopId: number | null = null;
    if (body.stopId) {
      const stop = route.stops.find((s) => s.id === Number(body.stopId));
      if (!stop) return NextResponse.json({ error: "Stop not on this route" }, { status: 400 });
      stopId = stop.id;
    }

    const existing = await prisma.transportMember.findUnique({
      where: { institutionId_studentId: { institutionId: session.institutionId, studentId } },
    });
    if (existing) return NextResponse.json({ error: "ALREADY_MEMBER" }, { status: 409 });

    // Default fare: route base + stop extra (or explicit override)
    const stopExtra = stopId
      ? Number(route.stops.find((s) => s.id === stopId)?.extraFare ?? 0)
      : 0;
    const monthlyFare =
      body.monthlyFare !== undefined && Number(body.monthlyFare) > 0
        ? Number(body.monthlyFare)
        : Number(route.baseFare) + stopExtra;

    const member = await prisma.transportMember.create({
      data: {
        institutionId: session.institutionId,
        studentId,
        routeId,
        stopId,
        monthlyFare,
        status: "ACTIVE",
      },
    });
    return NextResponse.json({ member });
  } catch {
    return NextResponse.json({ error: "Could not assign member" }, { status: 500 });
  }
}
