<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\DocStoreBundle\Security\Guard;

use Lexik\Bundle\JWTAuthenticationBundle\TokenExtractor\TokenExtractorInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Extract the JWT Token from the segment of the dav endpoints.
 *
 * A segment is a separation inside the string, using the character "/".
 *
 * For recognizing the JWT, the first segment must be "dav", and the second one must be
 * the JWT endpoint.
 */
final readonly class DavOnUrlTokenExtractor implements TokenExtractorInterface
{
    public function __construct(
        private LoggerInterface $logger,
    ) {}

    public function extract(Request $request): false|string
    {
        $uri = $request->getRequestUri();

        $segments = array_values(
            array_filter(
                explode('/', $uri),
                fn ($item) => '' !== trim($item)
            )
        );

        if (2 > count($segments)) {
            $this->logger->info('not enough segment for parsing URL');

            return false;
        }

        if ('dav' !== $segments[0]) {
            $this->logger->info('the first segment of the url must be DAV');

            return false;
        }

        return $segments[1];
    }
}
