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

/** Allocate a student to a hostel/room: { studentId, hostelId, roomId?, bedNo?, monthlyFee? }. */
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 hostelId = Number(body.hostelId);
    if (!studentId || !hostelId) {
      return NextResponse.json({ error: "Missing fields" }, { status: 400 });
    }

    const [student, hostel] = await Promise.all([
      prisma.student.findFirst({
        where: { id: studentId, institutionId: session.institutionId, status: "ACTIVE" },
      }),
      prisma.hostel.findFirst({
        where: { id: hostelId, institutionId: session.institutionId },
      }),
    ]);
    if (!student) return NextResponse.json({ error: "Student not found" }, { status: 404 });
    if (!hostel) return NextResponse.json({ error: "Hostel not found" }, { status: 404 });

    // Optional room — must belong to the chosen hostel and have a free bed
    let roomId: number | null = null;
    let defaultFee = Number(hostel.monthlyFee);
    if (body.roomId) {
      const room = await prisma.hostelRoom.findFirst({
        where: { id: Number(body.roomId), hostelId },
        include: { _count: { select: { allocations: { where: { status: "ACTIVE" } } } } },
      });
      if (!room) return NextResponse.json({ error: "ROOM_NOT_IN_HOSTEL" }, { status: 400 });
      if (room._count.allocations >= room.capacity) {
        return NextResponse.json({ error: "ROOM_FULL" }, { status: 409 });
      }
      roomId = room.id;
      if (Number(room.monthlyFee) > 0) defaultFee = Number(room.monthlyFee);
    }

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

    const member = await prisma.hostelMember.create({
      data: {
        institutionId: session.institutionId,
        studentId,
        hostelId,
        roomId,
        bedNo: String(body.bedNo ?? "").trim() || null,
        monthlyFee:
          body.monthlyFee !== undefined && Number(body.monthlyFee) > 0
            ? Number(body.monthlyFee)
            : defaultFee,
        joinDate: new Date(),
        status: "ACTIVE",
      },
    });
    return NextResponse.json({ member });
  } catch {
    return NextResponse.json({ error: "Could not allocate student" }, { status: 500 });
  }
}
