import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { requirePageRole, resolveSchoolId, ApiError } from "@/lib/auth";
import { handleApiError } from "@/lib/api-helpers";
import { effectiveFee } from "@/lib/constants";
import { ensureInstallmentSchedule } from "@/lib/installments";
import { INSTALLMENT_MONTHS, paymentDeadlineFor } from "@/lib/fee-schedule";

/**
 * كشف حساب الطالب التراكمي (v8.1):
 * - المبلغ الكلي للقسط + نسبة الخصم ومبلغه + القسط الصافي
 * - جدول الأقساط الثمانية (المبلغ، المسدد، المتبقي، تاريخ الاستحقاق، الحالة)
 * - سجل كل دفعة (المبلغ، تاريخ الدفع، رقم وصل القبض، طريقة الدفع، نوع القسط)
 * - المتبقي الكلي + ملخص
 */
export async function GET(_req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
  try {
    const viewer = await requirePageRole("students", "ADMIN", "ACCOUNTANT", "STAFF");
    const viewerSchoolId = await resolveSchoolId(viewer);
    const { id } = await ctx.params;

    const student = await db.student.findUnique({
      where: { id },
      include: {
        payments: {
          orderBy: { paidAt: "asc" },
          select: {
            id: true, receiptNumber: true, amount: true, installmentType: true,
            method: true, transactionRef: true, notes: true, paidAt: true,
            creator: { select: { fullName: true } },
          },
        },
      },
    });
    if (!student || student.schoolId !== viewerSchoolId) throw new ApiError("الطالب غير موجود", 404);

    // ضمان جدول الأقساط (ترحيل خلفي للطلاب القدامى)
    await ensureInstallmentSchedule(student.id);
    const installments = await db.installment.findMany({
      where: { studentId: student.id },
      orderBy: { seq: "asc" },
    });

    const grossFee = student.totalFee;
    const discountPercent = student.discountPercent;
    const discountAmount = Math.round(grossFee * (discountPercent / 100) * 100) / 100;
    const netFee = effectiveFee(grossFee, discountPercent);
    const paid = student.payments.reduce((s, p) => s + p.amount, 0);
    const remaining = Math.max(0, netFee - paid);
    const deadline = paymentDeadlineFor(student.registeredAt);

    return NextResponse.json({
      student: {
        id: student.id,
        studentCode: student.studentCode,
        nameAr: student.nameAr,
        nameEn: student.nameEn,
        grade: student.grade,
        classroom: student.classroom,
        guardianName: student.guardianName,
        guardianPhone: student.guardianPhone,
        registeredAt: student.registeredAt,
        isActive: student.isActive,
      },
      feeSummary: {
        grossFee,
        discountPercent,
        discountAmount,
        netFee,
        paid,
        remaining,
        installmentsCount: INSTALLMENT_MONTHS,
        monthlyInstallment: Math.round((netFee / INSTALLMENT_MONTHS) * 100) / 100,
        deadline,
        fullyPaid: remaining <= 0,
      },
      installments: installments.map((i) => ({
        seq: i.seq,
        dueDate: i.dueDate,
        amount: i.amount,
        paidAmount: i.paidAmount,
        remainingAmount: Math.max(0, i.amount - i.paidAmount),
        status: i.status,
      })),
      payments: student.payments.map((p) => ({
        id: p.id,
        receiptNumber: p.receiptNumber,
        amount: p.amount,
        installmentType: p.installmentType,
        method: p.method,
        transactionRef: p.transactionRef,
        notes: p.notes,
        paidAt: p.paidAt,
        by: p.creator?.fullName ?? null,
      })),
    });
  } catch (err) {
    return handleApiError(err);
  }
}
