<?php

namespace App\Http\Middleware;

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

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

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

        $admin = $user?->canAccessAdminPortal() ?? false;
        $this->sessions->terminate($request);

        return redirect()->to($admin ? '/admin/login' : route('login'))
            ->withErrors(['email' => __('auth.portal_denied')]);
    }
}
