<?php
namespace Incoviba\Middleware;

use GuzzleHttp\Psr7\Uri;
use Incoviba\Common\Alias\View;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Log\LoggerInterface;
use Incoviba\Service;

class Authentication
{
    public function __construct(
        protected ResponseFactoryInterface $responseFactory,
        protected Service\Login $service,
        protected LoggerInterface $logger,
        protected View $view,
        protected string $login_url) {}

    public function __invoke(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        if ($this->service->isIn() or $this->isValid($request)) {
            return $handler->handle($request);
        }
        $this->logger->notice("Not logged in.", [
            'REMOTE_ADDR' => $request->getServerParams()['REMOTE_ADDR'],
            'REQUEST_URI' => $request->getServerParams()['REQUEST_URI']
        ]);
        $response = $this->responseFactory->createResponse(307, 'Not logged in')
            ->withHeader('Referer', (string) $request->getUri())
            ->withHeader('X-Redirected-URI', (string) $request->getUri());
        $url = "{$request->getUri()}";
        if (str_ends_with($url, '/login')) {
            $url = str_replace('/login', '', $url);
        }
        return $this->view->render($response, 'login.form', ['redirect_uri' => $url]);
    }

    protected function isValid(ServerRequestInterface $request): bool
    {
        $uri = $request->getUri();
        $current_path = $uri->getPath();
        $current_url = implode('', [
            $uri->getHost() . ($uri->getPort() !== null ? ":{$uri->getPort()}" : ''),
            $uri->getPath()
        ]);

        $valid_paths = [
            '/'
        ];
        if (in_array($current_path, $valid_paths, true)) {
            return true;
        }
        $valid_subpaths = [
            '/api/'
        ];
        foreach ($valid_subpaths as $path) {
            if (str_starts_with($current_path, $path)) {
                return true;
            }
        }
        $login = new Uri($this->login_url);
        $login_url = implode('', [
            $login->getHost() . ($login->getPort() !== null ? ":{$login->getPort()}" : ''),
            $login->getPath()
        ]);
        $valid_uris = [
            $login_url,
            "{$login_url}/",
        ];
        if (in_array($current_url, $valid_uris, true)) {
            return true;
        }
        return false;
    }
}
