<?php

namespace App\Http\Middleware;

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

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

    public function handle(Request $request, Closure $next): Response
    {
        $guard = Filament::auth();
        if (! $guard->check()) {
            return redirect()->guest(Filament::getLoginUrl());
        }

        $user = $guard->user();
        if (! $user->canAccessAdminPortal()) {
            $this->sessions->terminate($request);

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

        Auth::shouldUse(Filament::getAuthGuard());

        return $next($request);
    }
}
