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

/** Own salary payments (payslips) for teacher/staff logins. */
export async function GET() {
  const session = await requireAnyRole([...STAFF_SIDE_ROLES]);
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const me = await prisma.user.findUnique({
    where: { id: session.userId },
    select: { staffId: true },
  });
  if (!me?.staffId) return NextResponse.json({ payments: [] });

  const payments = await prisma.salaryPayment.findMany({
    where: { staffId: me.staffId },
    orderBy: { paidAt: "desc" },
    select: {
      id: true,
      month: true,
      amount: true,
      method: true,
      details: true,
      note: true,
      paidAt: true,
    },
  });

  return NextResponse.json({
    payments: payments.map((p) => ({ ...p, amount: Number(p.amount) })),
  });
}
