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

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

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

    const name = String(body.name ?? hostel.name).trim();
    if (!name) return NextResponse.json({ error: "Name required" }, { status: 400 });

    await prisma.hostel.update({
      where: { id: hostel.id },
      data: {
        name,
        nameBn: body.nameBn !== undefined ? String(body.nameBn).trim() || null : hostel.nameBn,
        type: HOSTEL_TYPES.includes(body.type as never) ? body.type : hostel.type,
        wardenName: body.wardenName !== undefined ? String(body.wardenName).trim() || null : hostel.wardenName,
        wardenPhone: body.wardenPhone !== undefined ? String(body.wardenPhone).trim() || null : hostel.wardenPhone,
        monthlyFee: body.monthlyFee !== undefined ? Math.max(0, Number(body.monthlyFee) || 0) : hostel.monthlyFee,
        isActive: typeof body.isActive === "boolean" ? body.isActive : hostel.isActive,
      },
    });
    return NextResponse.json({ success: true });
  } catch {
    return NextResponse.json({ error: "Could not update hostel" }, { status: 500 });
  }
}

/** Delete a hostel (only when no student is allocated to 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 hostel = await prisma.hostel.findFirst({
    where: { id: Number(id), institutionId: session.institutionId },
  });
  if (!hostel) return NextResponse.json({ error: "Not found" }, { status: 404 });

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

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