<?php
namespace App\Middleware;

use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Slim\Views\Blade as View;
use App\Service;

class Auth
{
    public function __construct(protected Service\Auth $service, protected ResponseFactoryInterface $responseFactory, protected View $view) {}

    public function __invoke(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        if ($this->skipRoutes($request) or $this->service->isIn()) {
            return $handler->handle($request);
        }
        return $this->redirect('guest');
    }

    protected function skipRoutes(ServerRequestInterface $request): bool
    {
        $uri = $request->getUri();
        $route = $uri->getPath();
        $routes = [
            '/guest',
            '/auth/login'
        ];
        return in_array($route, $routes, true);
    }
    protected function redirect(string $route): ResponseInterface
    {
        $response = $this->responseFactory->createResponse(301, 'Not authorized');
        return $this->view->render($response, $route);
    }
}
