import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { requirePageRole, resolveSchoolId, ApiError } from "@/lib/auth";
import { logAudit } from "@/lib/audit";
import { handleApiError } from "@/lib/api-helpers";
import { nextExpenseVoucherNumber } from "@/lib/voucher";
import { isValidExpenseKind, inferExpenseKind, EXPENSE_KIND_AR } from "@/lib/finance-kinds";

/** قائمة المصروفات + ملخص الميزانية (الإيرادات - المصروفات = الصافي) — نطاق المدرسة
 *  ?kind=MAINTENANCE — تصفية بالبند المالي الموحد (v8.1) */
export async function GET(req: NextRequest) {
  try {
    const user = await requirePageRole("finance", "ADMIN", "ACCOUNTANT");
    const schoolId = await resolveSchoolId(user, req.nextUrl.searchParams.get("schoolId"));
    const { searchParams } = new URL(req.url);
    const limit = Math.min(parseInt(searchParams.get("limit") || "50"), 300);
    const kindFilter = searchParams.get("kind")?.trim() ?? "";

    const [expenses, incomeAgg, expenseAgg, otherIncomeAgg] = await Promise.all([
      db.expense.findMany({
        where: { schoolId, ...(kindFilter ? { kind: kindFilter } : {}) },
        orderBy: { spentAt: "desc" },
        take: limit,
        include: { creator: { select: { fullName: true } } },
      }),
      db.payment.aggregate({ where: { schoolId }, _sum: { amount: true } }),
      db.expense.aggregate({ where: { schoolId }, _sum: { amount: true } }),
      db.otherIncome.aggregate({ where: { schoolId }, _sum: { amount: true } }),
    ]);

    // للسجلات القديمة بلا بند موحد: استنتاج البند من الفئة النصية عند العرض
    const expensesWithKind = expenses.map((e) => {
      const effKind = e.kind && e.kind !== "OTHER" ? e.kind : inferExpenseKind(e.category);
      return { ...e, kind: effKind, kindLabel: EXPENSE_KIND_AR[effKind] ?? "أخرى" };
    });

    const studentIncome = incomeAgg._sum.amount ?? 0;
    const otherIncome = otherIncomeAgg._sum.amount ?? 0;
    const totalIncome = studentIncome + otherIncome;
    const totalExpenses = expenseAgg._sum.amount ?? 0;

    return NextResponse.json({
      expenses: expensesWithKind,
      summary: {
        totalIncome,
        studentIncome,
        otherIncome,
        totalExpenses,
        netBalance: totalIncome - totalExpenses,
      },
    });
  } catch (err) {
    return handleApiError(err);
  }
}

/** إضافة مصروف جديد — رقم وصل الصرف + البند المالي الموحد (v8.1) */
export async function POST(req: NextRequest) {
  try {
    const user = await requirePageRole("finance", "ADMIN", "ACCOUNTANT", "SUPER_ADMIN");
    const schoolId = await resolveSchoolId(user, req.nextUrl.searchParams.get("schoolId"));
    const body = await req.json();
    const { category, description, amount, spentAt, invoiceName, invoiceData, kind, voucherNumber } =
      body as Record<string, string | undefined>;

    if (!category) throw new ApiError("فئة المصروف مطلوبة", 400);
    if (!description || String(description).trim().length < 2) {
      throw new ApiError("وصف المصروف مطلوب", 400);
    }
    const amt = Number(amount);
    if (isNaN(amt) || amt <= 0) throw new ApiError("مبلغ المصروف غير صالح", 400);
    if (invoiceData && invoiceData.length > 3_000_000) {
      throw new ApiError("حجم الملف المرفق كبير جداً (الحد الأقصى ~2 ميجابايت)", 400);
    }
    const spentDate = spentAt ? new Date(String(spentAt)) : new Date();
    // رقم وصل الصرف (v8.1): يدوي من السند الورقي أو توليد تلقائي SO-YYYY-####
    const voucher = voucherNumber && String(voucherNumber).trim()
      ? String(voucherNumber).trim()
      : await nextExpenseVoucherNumber(schoolId, spentDate);
    // البند المالي الموحد (v8.1): من القائمة أو استنتاجه من الفئة النصية
    const kindFinal = isValidExpenseKind(kind) ? kind : inferExpenseKind(String(category));

    const expense = await db.expense.create({
      data: {
        category: String(category),
        description: String(description).trim(),
        amount: amt,
        spentAt: spentDate,
        invoiceName: invoiceName ?? null,
        invoiceData: invoiceData ?? null,
        voucherNumber: voucher,
        kind: kindFinal,
        createdById: user.id,
        schoolId,
      },
      include: { creator: { select: { fullName: true } } },
    });

    await logAudit(user, {
      action: "CREATE",
      entity: "Expense",
      entityId: expense.id,
      details: `تسجيل مصروف: ${expense.description} - فئة: ${expense.category} - مبلغ: ${amt} - وصل صرف: ${voucher}`,
    });

    return NextResponse.json({ expense }, { status: 201 });
  } catch (err) {
    return handleApiError(err);
  }
}
