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";

/** تسديد سلفة منتسبين (v8.1) — يُسجل إيراداً تلقائياً ببند "تسديد سلف منتسبين" */
export async function POST(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
  try {
    const user = await requirePageRole("finance", "ADMIN", "ACCOUNTANT", "SUPER_ADMIN");
    const schoolId = await resolveSchoolId(user, req.nextUrl.searchParams.get("schoolId"));
    const { id } = await ctx.params;
    const body = (await req.json()) as Record<string, unknown>;
    const amount = Number(body.amount);
    const notes = body.notes == null || String(body.notes).trim() === "" ? null : String(body.notes).trim();
    const paidAt = body.paidAt ? new Date(String(body.paidAt)) : new Date();

    const loan = await db.employeeLoan.findFirst({
      where: { id, schoolId },
      include: { employee: { select: { name: true } }, repayments: { select: { amount: true } } },
    });
    if (!loan) throw new ApiError("السلفة غير موجودة", 404);
    if (!Number.isFinite(amount) || amount <= 0) throw new ApiError("مبلغ التسديد غير صالح", 400);
    const repaidSoFar = loan.repayments.reduce((s, r) => s + r.amount, 0);
    const remaining = loan.amount - repaidSoFar;
    if (remaining <= 0) throw new ApiError("السلفة مسددة بالكامل مسبقاً", 400);
    if (amount > remaining + 0.001) {
      throw new ApiError(`مبلغ التسديد يتجاوز المتبقي (${remaining})`, 400);
    }
    if (isNaN(paidAt.getTime())) throw new ApiError("تاريخ التسديد غير صالح", 400);

    const repayment = await db.$transaction(async (tx) => {
      const income = await tx.otherIncome.create({
        data: {
          source: `تسديد سلفة — ${loan.employee.name}`,
          reason: loan.reason,
          amount,
          kind: "STAFF_LOAN_REPAY",
          notes,
          receivedAt: paidAt,
          createdById: user.id,
          schoolId,
        },
      });
      return tx.employeeLoanRepayment.create({
        data: {
          loanId: loan.id,
          amount,
          paidAt,
          notes,
          otherIncomeId: income.id,
          creatorId: user.id,
          schoolId,
        },
      });
    });

    await logAudit(user, {
      action: "CREATE",
      entity: "EmployeeLoanRepayment",
      entityId: repayment.id,
      details: `تسديد سلفة الموظف ${loan.employee.name} — مبلغ: ${amount} — المتبقي: ${Math.max(0, remaining - amount)}`,
    });
    return NextResponse.json({ repayment }, { status: 201 });
  } catch (err) {
    return handleApiError(err);
  }
}
