<?php

namespace App\Http\Middleware;

use App\Exceptions\Pouzivatel\PouzivatelJeBlokovany;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Class UserIsNotBlocked
 */
class UserIsNotBlocked
{
    /**
     * Handle an incoming request.
     *
     *
     * @throws \App\Exceptions\pouzivatel\PouzivatelJeBlokovany
     */
    public function handle(Request $request, Closure $next): Response
    {
        if (auth()->check()) {
            $user = $request->user();

            if ($user->jeBlokovany() === true) {
                auth()->logout();
                throw new PouzivatelJeBlokovany($user, $this->redirectTo($request));
            }
        }

        return $next($request);
    }

    /**
     * Get the path the user should be redirected to when they are not authenticated.
     */
    protected function redirectTo(Request $request): ?string
    {
        if (! $request->expectsJson()) {
            return route('login.form');
        }
    }
}
