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

/** تسجيل دفعة لشركة — تُنشئ مصروفاً تلقائياً بفئة فواتير الشركات */
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 { supplierId, invoiceId, amount, paidAt, notes } = body as Record<string, string | undefined>;

    if (!supplierId) throw new ApiError("الشركة مطلوبة", 400);
    const supplier = await db.supplier.findFirst({ where: { id: supplierId, deletedAt: null, schoolId } });
    if (!supplier) throw new ApiError("الشركة غير موجودة", 404);

    if (invoiceId) {
      const invoice = await db.supplierInvoice.findUnique({ where: { id: invoiceId } });
      if (!invoice || invoice.supplierId !== supplierId) {
        throw new ApiError("الفاتورة المحددة لا تنتمي لهذه الشركة", 400);
      }
    }

    const amt = Number(amount);
    if (isNaN(amt) || amt <= 0) throw new ApiError("مبلغ الدفعة غير صالح", 400);
    const date = paidAt ? new Date(String(paidAt)) : new Date();
    if (isNaN(date.getTime())) throw new ApiError("تاريخ الدفع غير صالح", 400);

    const payment = await db.$transaction(async (tx) => {
      const expense = await tx.expense.create({
        data: {
          category: "فواتير الشركات",
          description: `دفعة لشركة ${supplier.name}`,
          amount: amt,
          spentAt: date,
          createdById: user.id,
          schoolId,
        },
      });
      return tx.supplierPayment.create({
        data: {
          supplierId,
          invoiceId: invoiceId || null,
          amount: amt,
          paidAt: date,
          notes: notes && String(notes).trim() ? String(notes).trim() : null,
          expenseId: expense.id,
          creatorId: user.id,
        },
        include: { supplier: { select: { name: true } } },
      });
    });

    await logAudit(user, {
      action: "CREATE",
      entity: "SupplierPayment",
      entityId: payment.id,
      details: `دفعة لشركة ${supplier.name} — مبلغ: ${amt} (أُنشئ مصروف تلقائي)`,
    });

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