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

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

/** Update a room. */
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 room = await prisma.hostelRoom.findFirst({
      where: { id: Number(id), institutionId: session.institutionId },
    });
    if (!room) return NextResponse.json({ error: "Not found" }, { status: 404 });

    const roomNo = String(body.roomNo ?? room.roomNo).trim();
    if (!roomNo) return NextResponse.json({ error: "Room no required" }, { status: 400 });

    // If the room is being moved to another hostel, verify the target + uniqueness
    let hostelId = room.hostelId;
    if (body.hostelId && Number(body.hostelId) !== room.hostelId) {
      const hostel = await prisma.hostel.findFirst({
        where: { id: Number(body.hostelId), institutionId: session.institutionId },
      });
      if (!hostel) return NextResponse.json({ error: "Hostel not found" }, { status: 404 });
      hostelId = hostel.id;
    }

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

    const capacity =
      body.capacity !== undefined ? Math.max(1, Number(body.capacity) || 1) : room.capacity;
    const occupied = await prisma.hostelMember.count({
      where: { roomId: room.id, status: "ACTIVE" },
    });
    if (capacity < occupied) {
      return NextResponse.json({ error: "CAPACITY_BELOW_OCCUPANCY" }, { status: 409 });
    }

    await prisma.hostelRoom.update({
      where: { id: room.id },
      data: {
        hostelId,
        roomNo,
        floor: body.floor !== undefined ? Math.max(0, Number(body.floor) || 0) : room.floor,
        capacity,
        roomType: ROOM_TYPES.includes(body.roomType as never) ? body.roomType : room.roomType,
        monthlyFee:
          body.monthlyFee !== undefined ? Math.max(0, Number(body.monthlyFee) || 0) : room.monthlyFee,
      },
    });
    return NextResponse.json({ success: true });
  } catch {
    return NextResponse.json({ error: "Could not update room" }, { status: 500 });
  }
}

/** Delete a room (only when nobody lives in 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 room = await prisma.hostelRoom.findFirst({
    where: { id: Number(id), institutionId: session.institutionId },
  });
  if (!room) return NextResponse.json({ error: "Not found" }, { status: 404 });

  const allocations = await prisma.hostelMember.count({ where: { roomId: room.id } });
  if (allocations > 0) return NextResponse.json({ error: "IN_USE" }, { status: 409 });

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