<?php

namespace App\Http\Middleware;

use App\Services\Audit\AuditLogService;
use Closure;

class AuditSystemActivity
{
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        if ($request->user() && $this->shouldAudit($request)) {
            app(AuditLogService::class)->record($request, $response, $this->statusFor($response));
        }

        return $response;
    }

    private function shouldAudit($request): bool
    {
        if ($request->is('audit/logs*')) {
            return false;
        }

        return $request->is('dashboard*')
            || $request->is('dataentry*')
            || $request->is('analysis*')
            || $request->is('settings*')
            || $request->is('resources*')
            || $request->is('location*')
            || $request->is('indicator*')
            || $request->is('partner*')
            || $request->is('users*')
            || $request->is('roles*')
            || $request->is('integrations*');
    }

    private function statusFor($response): string
    {
        $code = method_exists($response, 'getStatusCode') ? $response->getStatusCode() : 200;
        return $code >= 400 ? 'failed' : 'success';
    }
}
