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

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

/** Update a resident's hostel/room/bed/fee/status (change or clear 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 member = await prisma.hostelMember.findFirst({
      where: { id: Number(id), institutionId: session.institutionId },
    });
    if (!member) return NextResponse.json({ error: "Not found" }, { status: 404 });

    let hostelId = member.hostelId;
    if (body.hostelId && Number(body.hostelId) !== member.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;
    }

    // Room may be changed, moved with the new hostel, or cleared
    let roomId: number | null = member.roomId;
    if (body.roomId !== undefined) {
      if (!body.roomId || Number(body.roomId) === 0) {
        roomId = null;
      } else {
        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 });
        const currentInRoom = room._count.allocations - (member.roomId === room.id ? 1 : 0);
        if (member.roomId !== room.id && currentInRoom >= room.capacity) {
          return NextResponse.json({ error: "ROOM_FULL" }, { status: 409 });
        }
        roomId = room.id;
      }
    }

    await prisma.hostelMember.update({
      where: { id: member.id },
      data: {
        hostelId,
        roomId,
        bedNo:
          body.bedNo !== undefined ? String(body.bedNo ?? "").trim() || null : member.bedNo,
        monthlyFee:
          body.monthlyFee !== undefined && Number(body.monthlyFee) >= 0
            ? Number(body.monthlyFee)
            : member.monthlyFee,
        status: body.status === "INACTIVE" ? "INACTIVE" : body.status === "ACTIVE" ? "ACTIVE" : member.status,
      },
    });
    return NextResponse.json({ success: true });
  } catch {
    return NextResponse.json({ error: "Could not update resident" }, { status: 500 });
  }
}

/** Vacate a student from the hostel (keeps past attendance records). */
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 member = await prisma.hostelMember.findFirst({
    where: { id: Number(id), institutionId: session.institutionId },
  });
  if (!member) return NextResponse.json({ error: "Not found" }, { status: 404 });

  await prisma.$transaction([
    prisma.hostelAttendance.deleteMany({ where: { memberId: member.id } }),
    prisma.hostelMember.delete({ where: { id: member.id } }),
  ]);
  return NextResponse.json({ success: true });
}
