<?php

namespace Maestro\Core\Http\Middleware;

use Carbon\Carbon;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;

class AbsoluteSessionTimeout
{
    /**
     * Handle an incoming request.
     * 
     * Enforces the hard 8-12 hour boundary. Laravel's built-in `SESSION_LIFETIME` only handles idle timeout.
     * This middleware checks `session_started_at` and destroys the session if the absolute timeout is exceeded.
     */
    public function handle(Request $request, Closure $next): Response
    {
        $startedAt = session('session_started_at');
        $maxLifetime = (int) config('session.absolute_timeout', 720); // minutes, default: 12 hours

        if ($startedAt && now()->diffInMinutes(Carbon::parse($startedAt)) > $maxLifetime) {
            $user = $request->user();

            // Destroy session
            session()->invalidate();
            session()->regenerateToken();

            if ($user && class_exists(\App\Services\Microsoft\MicrosoftTokenService::class)) {
                app(\App\Services\Microsoft\MicrosoftTokenService::class)->revokeTokens($user);
            }

            Log::info('Absolute session timeout reached', [
                'user_id'    => $user?->id,
                'started_at' => $startedAt,
                'max_lifetime' => $maxLifetime,
            ]);

            return response()->json([
                'message'      => 'Session expired. Please log in again.',
                'force_reauth' => true,
            ], 401);
        }

        return $next($request);
    }
}
