<?php

namespace App\Service\ApiLegacy;

use App\Service\Rest\ApiRequestService;
use JetBrains\PhpStorm\Pure;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Security\Core\Authentication\Token\NullToken;
use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
use Symfony\Component\Security\Core\Security;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;

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

    /** @noinspection PhpPossiblePolymorphicInvocationInspection */
    public function request(
        string $method,
        string $url,
        array $parameters = [],
        array $options = []
    ): ResponseInterface {

        $token = $this->security->getToken();
        if ($token === null || $token instanceof NullToken || $token->getUser() === null) {
            throw new HttpException(500, 'Request error : Invalid security token');
        }

        if (!array_key_exists('BEARER', $_REQUEST)) {
            throw new HttpException(500, 'Request error : missing BEARER');
        }

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

        if ($token instanceof SwitchUserToken) {
            $originalUser = $token->getOriginalToken()->getUser();
            if ($originalUser === null) {
                throw new HttpException(500, 'Request error : Switch original user missing');
            }

            $headers['x-accessid'] = $originalUser->getId();
            $headers['x-switch-access'] = $token->getUser()->getId();
        } else {
            $headers['x-accessid'] = $token->getUser()->getId();
        }

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

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

}
