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 PATCH(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
  try {
    const user = await requirePageRole("finance", "ADMIN", "SUPER_ADMIN");
    const schoolId = await resolveSchoolId(user, req.nextUrl.searchParams.get("schoolId"));
    const { id } = await ctx.params;
    const expense = await db.expense.findUnique({
      where: { id },
      include: {
        employeePayments: { select: { id: true } },
        supplierPayments: { select: { id: true } },
      },
    });
    if (!expense || expense.schoolId !== schoolId) throw new ApiError("المصروف غير موجود", 404);
    if (expense.employeePayments.length > 0 || expense.supplierPayments.length > 0) {
      throw new ApiError("هذا المصروف مرتبط بدفعة راتب أو دفعة شركة — عدّله من صفحته الخاصة", 400);
    }

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

    if (category !== undefined) {
      if (!String(category).trim()) throw new ApiError("فئة المصروف مطلوبة", 400);
      data.category = String(category).trim();
    }
    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 (spentAt !== undefined) {
      const date = new Date(String(spentAt));
      if (isNaN(date.getTime())) throw new ApiError("تاريخ المصروف غير صالح", 400);
      data.spentAt = date;
    }
    if (Object.keys(data).length === 0) throw new ApiError("لا توجد بيانات للتعديل", 400);

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

/** حذف مصروف (مدير فقط) */
export async function DELETE(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
  try {
    const user = await requirePageRole("finance", "ADMIN", "SUPER_ADMIN");
    const schoolId = await resolveSchoolId(user, req.nextUrl.searchParams.get("schoolId"));
    const { id } = await ctx.params;
    const expense = await db.expense.findUnique({ where: { id } });
    if (!expense || expense.schoolId !== schoolId) throw new ApiError("المصروف غير موجود", 404);
    await db.expense.delete({ where: { id } });
    await logAudit(user, {
      action: "DELETE",
      entity: "Expense",
      entityId: id,
      details: `حذف مصروف: ${expense.description} - مبلغ: ${expense.amount}`,
    });
    return NextResponse.json({ ok: true });
  } catch (err) {
    return handleApiError(err);
  }
}
