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

/** سجل الحركات الأمني - المدير فقط */
export async function GET(req: NextRequest) {
  try {
    await requirePageRole("audit", "ADMIN");
    const { searchParams } = new URL(req.url);
    const limit = Math.min(parseInt(searchParams.get("limit") || "100"), 500);
    const action = searchParams.get("action") || "";
    const where: Record<string, unknown> = {};
    if (action) where.action = action;
    const logs = await db.auditLog.findMany({
      where,
      orderBy: { createdAt: "desc" },
      take: limit,
    });
    return NextResponse.json({ logs });
  } catch (err) {
    return handleApiError(err);
  }
}
