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

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

/** Update a staff member of this institution. */
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 employeeCode = String(body.employeeCode ?? "").trim();
    const name = String(body.name ?? "").trim();
    const phone = String(body.phone ?? "").trim();
    const designation = String(body.designation ?? "").trim();
    if (!employeeCode || !name || !phone || !designation) {
      return NextResponse.json({ error: "Missing fields" }, { status: 400 });
    }

    const staff = await prisma.staff.findFirst({
      where: { id: Number(id), institutionId: session.institutionId },
    });
    if (!staff) return NextResponse.json({ error: "Not found" }, { status: 404 });

    if (employeeCode !== staff.employeeCode) {
      const exists = await prisma.staff.findUnique({
        where: {
          institutionId_employeeCode: {
            institutionId: session.institutionId,
            employeeCode,
          },
        },
      });
      if (exists) return NextResponse.json({ error: "CODE_EXISTS" }, { status: 409 });
    }

    await prisma.staff.update({
      where: { id: staff.id },
      data: {
        employeeCode,
        name,
        nameBn: String(body.nameBn ?? "").trim() || null,
        gender: ["MALE", "FEMALE", "OTHER"].includes(body.gender) ? body.gender : staff.gender,
        dob: body.dob ? new Date(body.dob) : null,
        phone,
        email: String(body.email ?? "").trim() || null,
        address: String(body.address ?? "").trim() || null,
        designation,
        department: String(body.department ?? "").trim() || null,
        joinDate: body.joinDate ? new Date(body.joinDate) : null,
        monthlySalary: body.monthlySalary !== undefined ? Number(body.monthlySalary) : staff.monthlySalary,
        status: body.status === "INACTIVE" ? "INACTIVE" : "ACTIVE",
      },
    });
    return NextResponse.json({ success: true });
  } catch {
    return NextResponse.json({ error: "Could not update staff" }, { status: 500 });
  }
}

/** Delete a staff member (only when no attendance/leave/salary history). */
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 staff = await prisma.staff.findFirst({
    where: { id: Number(id), institutionId: session.institutionId },
  });
  if (!staff) return NextResponse.json({ error: "Not found" }, { status: 404 });

  const [attendance, leaves, salaries, issues, schedules] = await Promise.all([
    prisma.staffAttendance.count({ where: { staffId: staff.id } }),
    prisma.leaveRequest.count({ where: { staffId: staff.id } }),
    prisma.salaryPayment.count({ where: { staffId: staff.id } }),
    prisma.bookIssue.count({ where: { staffId: staff.id } }),
    prisma.classSchedule.count({ where: { staffId: staff.id } }),
  ]);
  if (attendance + leaves + salaries + issues + schedules > 0) {
    return NextResponse.json({ error: "IN_USE" }, { status: 409 });
  }

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