<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureUserNotSuspended
{
    public function handle(Request $request, Closure $next): Response
    {
        // Allow impersonation stop even for suspended users
        if ($request->is('impersonate/stop') && $request->session()->has('impersonator_id')) {
            return $next($request);
        }

        $user = $request->user();

        if ($user?->isSuspended()) {
            abort(403, 'Your account has been suspended.');
        }

        if (method_exists($user, 'isBanned') && $user?->isBanned()) {
            abort(403, 'Your account has been banned.');
        }

        return $next($request);
    }
}
