<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api\V1\Admin;

use App\Http\Controllers\Controller;
use App\Models\AuditLog;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

class AuditLogController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $user = $request->user();
        if (! $user || ! $user->hasRole('super_admin')) {
            throw new AccessDeniedHttpException('SUPER_ADMIN_ONLY');
        }

        $q = AuditLog::query()->withoutGlobalScope('tenant');

        if ($action = $request->query('action')) {
            $q->where('action', $action);
        }
        if ($userId = $request->query('user_id')) {
            $q->where('user_id', $userId);
        }
        if ($tenantId = $request->query('tenant_id')) {
            $q->where('tenant_id', $tenantId);
        }
        if ($modelType = $request->query('model_type')) {
            $q->where('model_type', $modelType);
        }
        if ($from = $request->query('from')) {
            $q->where('created_at', '>=', $from);
        }
        if ($to = $request->query('to')) {
            $q->where('created_at', '<=', $to);
        }

        $logs = $q->orderByDesc('created_at')->paginate((int) $request->query('per_page', 50));

        return response()->json(['data' => $logs]);
    }
}
