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 payment = await db.supplierPayment.findUnique({
      where: { id },
      include: { supplier: { select: { name: true } } },
    });
    if (!payment) throw new ApiError("الدفعة غير موجودة", 404);

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

    let amt = payment.amount;
    if (amount !== undefined) {
      amt = Number(amount);
      if (isNaN(amt) || amt <= 0) throw new ApiError("مبلغ الدفعة غير صالح", 400);
      data.amount = amt;
    }
    let date = payment.paidAt;
    if (paidAt !== undefined) {
      date = new Date(String(paidAt));
      if (isNaN(date.getTime())) throw new ApiError("تاريخ الدفع غير صالح", 400);
      data.paidAt = date;
    }
    if (notes !== undefined) {
      data.notes = notes && String(notes).trim() ? String(notes).trim() : null;
    }
    if (invoiceId !== undefined) {
      if (invoiceId) {
        const invoice = await db.supplierInvoice.findUnique({ where: { id: invoiceId } });
        if (!invoice || invoice.supplierId !== payment.supplierId) {
          throw new ApiError("الفاتورة المحددة لا تنتمي لهذه الشركة", 400);
        }
        data.invoiceId = invoiceId;
      } else {
        data.invoiceId = null;
      }
    }
    if (Object.keys(data).length === 0) throw new ApiError("لا توجد بيانات للتعديل", 400);

    const updated = await db.$transaction(async (tx) => {
      // مزامنة المصروف المرتبط ليبقى الرصيد صحيحاً
      if (payment.expenseId) {
        await tx.expense.update({
          where: { id: payment.expenseId },
          data: { amount: amt, spentAt: date },
        });
      }
      return tx.supplierPayment.update({ where: { id }, data });
    });

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

    return NextResponse.json({ payment: 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 payment = await db.supplierPayment.findUnique({
      where: { id },
      include: { supplier: { select: { name: true } } },
    });
    if (!payment) throw new ApiError("الدفعة غير موجودة", 404);

    await db.$transaction(async (tx) => {
      if (payment.expenseId) {
        await tx.expense.delete({ where: { id: payment.expenseId } });
      }
      await tx.supplierPayment.delete({ where: { id } });
    });

    await logAudit(user, {
      action: "DELETE",
      entity: "SupplierPayment",
      entityId: id,
      details: `حذف دفعة شركة ${payment.supplier.name} — مبلغ: ${payment.amount} (حُذف المصروف المرتبط وعاد الرصيد)`,
    });

    return NextResponse.json({ ok: true });
  } catch (err) {
    return handleApiError(err);
  }
}
