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

/** Fee statement + payment history of the caller's own (child's) record. */
export async function GET() {
  const session = await requireAnyRole(["STUDENT", "PARENT"]);
  if (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const studentId = await getMemberStudentId(session.userId);
  if (!studentId) {
    return NextResponse.json({ error: "NO_LINKED_STUDENT" }, { status: 409 });
  }

  const [schedules, payments, student] = await Promise.all([
    prisma.feeSchedule.findMany({
      where: { studentId },
      orderBy: [{ dueDate: "asc" }, { id: "asc" }],
      select: {
        id: true,
        title: true,
        amount: true,
        dueDate: true,
        month: true,
        note: true,
        feeHead: { select: { name: true, nameBn: true } },
        payments: { select: { amount: true }, where: {} },
      },
    }),
    prisma.feeCollection.findMany({
      where: { studentId },
      orderBy: { paidAt: "desc" },
      select: {
        id: true,
        invoiceNo: true,
        amount: true,
        method: true,
        paidAt: true,
        feeSchedule: { select: { title: true } },
      },
    }),
    prisma.student.findUnique({
      where: { id: studentId },
      select: { name: true, roll: true },
    }),
  ]);

  const statement = schedules.map((s) => {
    const paid = s.payments.reduce((sum, p) => sum + Number(p.amount), 0);
    const total = Number(s.amount);
    return {
      id: s.id,
      title: s.title,
      headName: s.feeHead?.name ?? null,
      headNameBn: s.feeHead?.nameBn ?? null,
      amount: total,
      paid,
      due: Math.max(0, total - paid),
      status: paid >= total ? "PAID" : paid > 0 ? "PARTIAL" : "DUE",
      dueDate: s.dueDate,
      month: s.month,
    };
  });

  const assigned = statement.reduce((sum, s) => sum + s.amount, 0);
  const paidTotal = statement.reduce((sum, s) => sum + s.paid, 0);

  return NextResponse.json({
    studentName: student?.name ?? null,
    roll: student?.roll ?? null,
    statement,
    payments: payments.map((p) => ({
      id: p.id,
      invoiceNo: p.invoiceNo,
      amount: Number(p.amount),
      method: p.method,
      paidAt: p.paidAt,
      title: p.feeSchedule?.title ?? null,
    })),
    totals: {
      assigned,
      paid: paidTotal,
      due: Math.max(0, assigned - paidTotal),
    },
  });
}
