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

/** Online payment claims submitted by students/parents — institution review
    list. ?status=PENDING (default) | APPROVED | REJECTED | ALL */
export async function GET(req: Request) {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const status = new URL(req.url).searchParams.get("status") ?? "PENDING";
  const claims = await prisma.feePaymentClaim.findMany({
    where: {
      institutionId: session.institutionId,
      ...(status !== "ALL" && ["PENDING", "APPROVED", "REJECTED"].includes(status) ? { status } : {}),
    },
    orderBy: { createdAt: "desc" },
    take: 200,
    select: {
      id: true,
      amount: true,
      method: true,
      accountLabel: true,
      details: true,
      note: true,
      status: true,
      decisionNote: true,
      decidedAt: true,
      createdAt: true,
      student: { select: { id: true, roll: true, name: true } },
      feeSchedule: { select: { id: true, title: true, month: true } },
      collection: { select: { invoiceNo: true } },
    },
  });

  const pendingCount = await prisma.feePaymentClaim.count({
    where: { institutionId: session.institutionId, status: "PENDING" },
  });

  return NextResponse.json({
    pendingCount,
    claims: claims.map((c) => ({
      id: c.id,
      amount: Number(c.amount),
      method: c.method,
      accountLabel: c.accountLabel,
      details: c.details ?? null,
      note: c.note,
      status: c.status,
      decisionNote: c.decisionNote,
      decidedAt: c.decidedAt,
      createdAt: c.createdAt,
      student: c.student,
      feeScheduleId: c.feeSchedule?.id ?? null,
      feeTitle: c.feeSchedule?.title ?? null,
      month: c.feeSchedule?.month ?? null,
      invoiceNo: c.collection?.invoiceNo ?? null,
    })),
  });
}
