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

/** Add a room to a hostel. */
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 hostelId = Number(body.hostelId);
    const roomNo = String(body.roomNo ?? "").trim();
    if (!hostelId || !roomNo) {
      return NextResponse.json({ error: "Missing fields" }, { status: 400 });
    }

    const hostel = await prisma.hostel.findFirst({
      where: { id: hostelId, institutionId: session.institutionId },
    });
    if (!hostel) return NextResponse.json({ error: "Hostel not found" }, { status: 404 });

    const duplicate = await prisma.hostelRoom.findUnique({
      where: { hostelId_roomNo: { hostelId, roomNo } },
    });
    if (duplicate) return NextResponse.json({ error: "DUPLICATE_ROOM" }, { status: 409 });

    const room = await prisma.hostelRoom.create({
      data: {
        institutionId: session.institutionId,
        hostelId,
        roomNo,
        floor: Math.max(0, Number(body.floor) || 0),
        capacity: Math.max(1, Number(body.capacity) || 1),
        roomType: ROOM_TYPES.includes(body.roomType as never) ? body.roomType : "SHARED",
        monthlyFee: Math.max(0, Number(body.monthlyFee) || 0),
      },
    });
    return NextResponse.json({ room });
  } catch {
    return NextResponse.json({ error: "Could not create room" }, { status: 500 });
  }
}
