<?php

namespace App\Service\ApiLegacy;

use App\Service\Rest\ApiRequestService;
use JetBrains\PhpStorm\Pure;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Security\Core\Authentication\Token\NullToken;
use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;
use App\Entity\Access\Access;

/**
 * Service d'appel à l'API opentalent V1
 */
class ApiLegacyRequestService extends ApiRequestService
{
    #[Pure]
    public function __construct(
        HttpClientInterface                       $apiLegacyClient,
        private readonly Security                 $security,
        private readonly JWTTokenManagerInterface $jwtManager,
        readonly private string                   $internalRequestsToken
    )
    {
        parent::__construct($apiLegacyClient);
    }

    /**
     * @param string $method
     * @param string $url
     * @param array<mixed> $parameters
     * @param array<mixed> $options
     */
    public function request(
        string $method,
        string $url,
        array $parameters = [],
        array $options = []
    ): ResponseInterface {

        $token = $this->security->getToken();

        $headers = [
            'Accept' => '*/*',
            'Charset' => 'UTF-8',
            'Accept-Encoding' => 'gzip, deflate, br',
            'Content-Type' => 'application/ld+json',
        ];

        /** @var Access $activeUser */
        $activeUser = $token->getUser();

        $jwt = null;
        if ($token instanceof SwitchUserToken) {
            /** @var Access|null $originalUser */
            $originalUser = $token->getOriginalToken()->getUser();

            if ($originalUser === null) {
                throw new HttpException(500, 'Request error : Switch original user missing');
            }

            $jwt = $this->jwtManager->create($originalUser->getPerson());
            $headers['x-accessid'] = $originalUser->getId();
            $headers['x-switch-access'] = $activeUser->getId();
        } elseif ($token !== null && !($token instanceof NullToken) && $token->getUser() !== null) {
            $jwt = $this->jwtManager->create($activeUser->getPerson());
            $headers['x-accessid'] = $activeUser->getId();
        }

        if ($jwt !== null) {
            $headers['authorization'] = 'BEARER ' . $jwt;
        }

        // Add the internal requests token
        $headers['internal-requests-token'] = $this->internalRequestsToken;

        $options['headers'] = array_merge($options['headers'] ?? [], $headers);

        return parent::request($method, $url, $parameters, $options);
    }

}
