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", "ACCOUNTANT", "SUPER_ADMIN");
    const schoolId = await resolveSchoolId(user, req.nextUrl.searchParams.get("schoolId"));
    const { id } = await ctx.params;
    const existing = await db.otherIncome.findUnique({ where: { id } });
    if (!existing || existing.schoolId !== schoolId) throw new ApiError("الإيراد غير موجود", 404);

    const body = (await req.json()) as Record<string, unknown>;
    const data: {
      source?: string; reason?: string; amount?: number;
      notes?: string | null; receivedAt?: Date;
    } = {};

    if (body.source !== undefined) {
      const s = String(body.source).trim();
      if (s.length < 2) throw new ApiError("جهة الإيراد مطلوبة", 400);
      data.source = s;
    }
    if (body.reason !== undefined) {
      const r = String(body.reason).trim();
      if (r.length < 2) throw new ApiError("سبب الإيراد مطلوب", 400);
      data.reason = r;
    }
    if (body.amount !== undefined) {
      const amt = Number(body.amount);
      if (!Number.isFinite(amt) || amt <= 0) throw new ApiError("المبلغ غير صالح", 400);
      data.amount = amt;
    }
    if (body.notes !== undefined) {
      data.notes = body.notes == null || String(body.notes).trim() === "" ? null : String(body.notes).trim();
    }
    if (body.receivedAt !== undefined) {
      const d = new Date(String(body.receivedAt));
      if (isNaN(d.getTime())) throw new ApiError("التاريخ غير صالح", 400);
      data.receivedAt = d;
    }

    if (Object.keys(data).length === 0) throw new ApiError("لا توجد حقول للتعديل", 400);

    const income = await db.otherIncome.update({ where: { id }, data });
    await logAudit(user, {
      action: "UPDATE",
      entity: "OtherIncome",
      entityId: id,
      details: `تعديل إيراد آخر — جهة: ${income.source} — الحقول: ${Object.keys(data).join(", ")}`,
    });
    return NextResponse.json({ ok: true, income });
  } 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 existing = await db.otherIncome.findUnique({ where: { id } });
    if (!existing || existing.schoolId !== schoolId) throw new ApiError("الإيراد غير موجود", 404);

    await db.otherIncome.delete({ where: { id } });
    await logAudit(user, {
      action: "DELETE",
      entity: "OtherIncome",
      entityId: id,
      details: `حذف إيراد آخر — جهة: ${existing.source} — السبب: ${existing.reason} — المبلغ: ${existing.amount}`,
    });
    return NextResponse.json({ ok: true });
  } catch (err) {
    return handleApiError(err);
  }
}
