<?php
namespace Incoviba\Middleware;

use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Incoviba\Service;

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

    public function __invoke(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        if ($this->service->isIn() or $this->isValid($request)) {
            return $handler->handle($request);
        }
        $response = $this->responseFactory->createResponse(301, 'Not logged in');
        $uri = urlencode(base64_encode((string) $request->getUri()));
        return $response->withHeader('Location', implode('?', [$this->login_url, "url={$uri}"]))
            ->withHeader('Referer', (string) $request->getUri())
            ->withHeader('X-Redirected-URI', (string) $request->getUri());
    }

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

        $valid_paths = [
            '/',
        ];
        if (in_array($current_path, $valid_paths, true)) {
            return true;
        }
        $valid_uris = [
            $this->login_url,
        ];
        if (in_array($current_url, $valid_uris, true)) {
            return true;
        }
        return false;
    }
}
