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, description, amount, invoiceDate } = 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 (!description || String(description).trim().length < 2) {
      throw new ApiError("وصف الفاتورة مطلوب", 400);
    }
    const amt = Number(amount);
    if (isNaN(amt) || amt <= 0) throw new ApiError("مبلغ الفاتورة غير صالح", 400);
    const date = invoiceDate ? new Date(String(invoiceDate)) : new Date();
    if (isNaN(date.getTime())) throw new ApiError("تاريخ الفاتورة غير صالح", 400);

    const invoice = await db.supplierInvoice.create({
      data: {
        supplierId,
        description: String(description).trim(),
        amount: amt,
        invoiceDate: date,
      },
      include: { supplier: { select: { name: true } } },
    });

    await logAudit(user, {
      action: "CREATE",
      entity: "SupplierInvoice",
      entityId: invoice.id,
      details: `فاتورة جديدة من شركة ${supplier.name}: ${invoice.description} — مبلغ: ${amt}`,
    });

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