<?php

namespace App\Http\Middleware;

use App\Support\PortalSession;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureAdminPortalAccess
{
    public function __construct(private readonly PortalSession $sessions) {}

    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();
        if (! $user || $user->canAccessAdminPortal()) {
            return $next($request);
        }

        $this->sessions->terminate($request);

        return redirect()->route('login')->withErrors(['email' => __('auth.portal_denied')]);
    }
}
