<?php

namespace Maestro\Core\Http\Middleware;

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

class EnsureUserIsActive
{
    /**
     * Handle an incoming request.
     * 
     * Catches users who were deactivated after they logged in. Without this middleware,
     * a deactivated user's existing session would remain valid until it expires.
     */
    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();

        if (!$user || !$user->is_active) {
            session()->invalidate();
            session()->regenerateToken();

            Log::info('Inactive user attempted to access application', [
                'user_id' => $user?->id,
                'email'   => $user?->email,
            ]);

            return response()->json([
                'message'      => 'Your account has been deactivated. Contact your administrator.',
                'force_reauth' => true,
            ], 403);
        }

        return $next($request);
    }
}
