<?php

namespace App\Http\Middleware;

use App\Models\AuditLog;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureOperatingModeValid
{
    public function handle(Request $request, Closure $next): Response
    {
        if (session('operating_mode') === 'administration') {
            $startedAt = session('administration_mode_started_at');
            $limit = config('nestab.security.administration_session_minutes', 60);

            if (! $startedAt || now()->diffInMinutes($startedAt) >= $limit) {
                session()->put('operating_mode', 'operation');
                session()->forget('administration_mode_started_at');

                AuditLog::query()->create([
                    'actor_id' => $request->user()->id,
                    'branch_id' => session('active_branch_id'),
                    'event' => 'modo_administracao_expirado',
                    'description' => 'Regresso automático ao modo normal',
                    'ip_address' => $request->ip(),
                    'user_agent' => $request->userAgent(),
                ]);

                session()->flash('warning', 'O Modo de Administração expirou após '.$limit.' minutos.');
            }
        }

        $request->user()->forceFill(['last_seen_at' => now()])->saveQuietly();

        return $next($request);
    }
}
