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

function todayISO(): string {
  return new Date().toISOString().slice(0, 10);
}

function currentMonth(): string {
  return new Date().toISOString().slice(0, 7);
}

/** Staff directory + HR summary (today's attendance, pending leaves, payroll). */
export async function GET() {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const institutionId = session.institutionId;
  const today = new Date(todayISO());
  const month = currentMonth();

  const [staff, todayAttendance, pendingLeaves, activeSalaries, monthPayments] =
    await Promise.all([
      prisma.staff.findMany({
        where: { institutionId },
        orderBy: [{ status: "asc" }, { id: "asc" }],
      }),
      prisma.staffAttendance.findMany({
        where: { institutionId, date: today },
        select: { staffId: true, status: true },
      }),
      prisma.leaveRequest.count({ where: { institutionId, status: "PENDING" } }),
      prisma.staff.aggregate({
        where: { institutionId, status: "ACTIVE" },
        _sum: { monthlySalary: true },
      }),
      prisma.salaryPayment.aggregate({
        where: { institutionId, month },
        _sum: { amount: true },
      }),
    ]);

  const payroll = Number(activeSalaries._sum.monthlySalary ?? 0);
  const paid = Number(monthPayments._sum.amount ?? 0);

  return NextResponse.json({
    staff: staff.map((s) => ({
      id: s.id,
      employeeCode: s.employeeCode,
      name: s.name,
      nameBn: s.nameBn,
      gender: s.gender,
      phone: s.phone,
      email: s.email,
      designation: s.designation,
      department: s.department,
      joinDate: s.joinDate,
      monthlySalary: Number(s.monthlySalary),
      photoUrl: s.photoUrl,
      signatureUrl: s.signatureUrl,
      status: s.status,
      todayStatus: todayAttendance.find((a) => a.staffId === s.id)?.status ?? null,
    })),
    summary: {
      totalStaff: staff.length,
      activeStaff: staff.filter((s) => s.status === "ACTIVE").length,
      presentToday: todayAttendance.filter((a) => a.status === "PRESENT").length,
      onLeaveToday: todayAttendance.filter((a) => a.status === "LEAVE").length,
      pendingLeaves,
      month,
      payroll,
      paidThisMonth: paid,
      dueThisMonth: Math.max(0, payroll - paid),
    },
  });
}

/** Add a staff member. */
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 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 exists = await prisma.staff.findUnique({
      where: { institutionId_employeeCode: { institutionId: session.institutionId, employeeCode } },
    });
    if (exists) return NextResponse.json({ error: "CODE_EXISTS" }, { status: 409 });

    const staff = await prisma.staff.create({
      data: {
        institutionId: session.institutionId,
        employeeCode,
        name,
        nameBn: String(body.nameBn ?? "").trim() || null,
        gender: ["MALE", "FEMALE", "OTHER"].includes(body.gender) ? body.gender : "MALE",
        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) : 0,
        status: "ACTIVE",
      },
    });
    return NextResponse.json({ staff });
  } catch {
    return NextResponse.json({ error: "Could not create staff" }, { status: 500 });
  }
}
