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 GET(req: NextRequest) {
  try {
    const viewer = await requirePageRole("finance", "ADMIN", "ACCOUNTANT");
    const schoolId = await resolveSchoolId(viewer, req.nextUrl.searchParams.get("schoolId"));
    const suppliers = await db.supplier.findMany({
      where: { deletedAt: null, schoolId },
      orderBy: { createdAt: "desc" },
      include: {
        invoices: { orderBy: { invoiceDate: "desc" } },
        payments: {
          orderBy: { paidAt: "desc" },
          include: { invoice: { select: { description: true } } },
        },
      },
    });
    const rows = suppliers.map((s) => {
      const totalInvoices = s.invoices.reduce((sum, i) => sum + i.amount, 0);
      const totalPaid = s.payments.reduce((sum, p) => sum + p.amount, 0);
      return { ...s, totalInvoices, totalPaid, debt: totalInvoices - totalPaid };
    });
    return NextResponse.json({ suppliers: rows });
  } catch (err) {
    return handleApiError(err);
  }
}

/** إضافة شركة جديدة */
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 { name, phone, notes } = body as Record<string, string | undefined>;

    if (!name || String(name).trim().length < 2) throw new ApiError("اسم الشركة مطلوب", 400);
    const trimmed = String(name).trim();
    const dup = await db.supplier.findFirst({ where: { name: trimmed, deletedAt: null, schoolId } });
    if (dup) throw new ApiError("توجد شركة مسجلة بهذا الاسم مسبقاً", 409);

    const supplier = await db.supplier.create({
      data: {
        name: trimmed,
        phone: phone && String(phone).trim() ? String(phone).trim() : null,
        notes: notes && String(notes).trim() ? String(notes).trim() : null,
        schoolId,
      },
    });

    await logAudit(user, {
      action: "CREATE",
      entity: "Supplier",
      entityId: supplier.id,
      details: `إضافة شركة: ${supplier.name}`,
    });

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