import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { requirePageRole, ApiError } from "@/lib/auth";
import { logAudit } from "@/lib/audit";
import { handleApiError } from "@/lib/api-helpers";

/** تعديل فاتورة شركة */
export async function PATCH(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
  try {
    const user = await requirePageRole("finance", "ADMIN", "ACCOUNTANT");
    const { id } = await ctx.params;
    const invoice = await db.supplierInvoice.findUnique({
      where: { id },
      include: { supplier: { select: { name: true } } },
    });
    if (!invoice) throw new ApiError("الفاتورة غير موجودة", 404);

    const body = await req.json();
    const { description, amount, invoiceDate } = body as Record<string, string | undefined>;
    const data: { description?: string; amount?: number; invoiceDate?: Date } = {};

    if (description !== undefined) {
      if (String(description).trim().length < 2) throw new ApiError("وصف الفاتورة مطلوب", 400);
      data.description = String(description).trim();
    }
    if (amount !== undefined) {
      const amt = Number(amount);
      if (isNaN(amt) || amt <= 0) throw new ApiError("مبلغ الفاتورة غير صالح", 400);
      data.amount = amt;
    }
    if (invoiceDate !== undefined) {
      const date = new Date(String(invoiceDate));
      if (isNaN(date.getTime())) throw new ApiError("تاريخ الفاتورة غير صالح", 400);
      data.invoiceDate = date;
    }
    if (Object.keys(data).length === 0) throw new ApiError("لا توجد بيانات للتعديل", 400);

    const updated = await db.supplierInvoice.update({ where: { id }, data });
    await logAudit(user, {
      action: "UPDATE",
      entity: "SupplierInvoice",
      entityId: id,
      details: `تعديل فاتورة شركة ${invoice.supplier.name}: ${updated.description} — المبلغ الجديد: ${updated.amount}`,
    });
    return NextResponse.json({ invoice: updated });
  } catch (err) {
    return handleApiError(err);
  }
}

/** حذف فاتورة — ممنوع إذا كانت مرتبطة بدفعات — مدير فقط */
export async function DELETE(_req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
  try {
    const user = await requirePageRole("finance", "ADMIN");
    const { id } = await ctx.params;
    const invoice = await db.supplierInvoice.findUnique({
      where: { id },
      include: { supplier: { select: { name: true } } },
    });
    if (!invoice) throw new ApiError("الفاتورة غير موجودة", 404);

    const linked = await db.supplierPayment.count({ where: { invoiceId: id } });
    if (linked > 0) {
      throw new ApiError(
        `لا يمكن حذف الفاتورة — مرتبطة بـ ${linked} دفعة/دفعات. احذف الدفعات المرتبطة أولاً أو عدّلها`,
        400
      );
    }

    await db.supplierInvoice.delete({ where: { id } });
    await logAudit(user, {
      action: "DELETE",
      entity: "SupplierInvoice",
      entityId: id,
      details: `حذف فاتورة شركة ${invoice.supplier.name}: ${invoice.description} — مبلغ: ${invoice.amount}`,
    });
    return NextResponse.json({ ok: true });
  } catch (err) {
    return handleApiError(err);
  }
}
