<?php

namespace App\Http\Middleware;

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

class EnsureGuest
{
    public function handle(Request $request, Closure $next): Response
    {
        $guard = Auth::guard('guest');

        if (! $guard->check()) {
            return redirect()->route('guest.login');
        }

        $guest = $guard->user();

        if (! $guest || $guest->status !== 'active') {
            $guard->logout();

            return redirect()
                ->route('guest.login')
                ->withErrors(['phone' => 'Доступ разрешён только активному гостю.']);
        }

        return $next($request);
    }
}
