<?php

declare(strict_types=1);

namespace App\State\Provider\Access;

use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\ApiResources\Profile\AccessProfile;
use App\Entity\Access\Access;
use App\Service\Access\AccessProfileCreator;
use Exception;
use RuntimeException;
use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
use Symfony\Bundle\SecurityBundle\Security;

/**
 * Class AccessProfileProvider : custom provider pour assurer l'alimentation de la réponse du GET my_profile
 * @package App\DataProvider\Access
 */
final class AccessProfileProvider implements ProviderInterface
{
    public function __construct(
        private Security $security,
        private AccessProfileCreator $accessProfileCreator
    )
    { }

    /**
     * @param Operation $operation
     * @param mixed[] $uriVariables
     * @param mixed[] $context
     * @return AccessProfile|null
     * @throws Exception
     */
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): ?AccessProfile
    {
        if($operation instanceof GetCollection) {
            throw new RuntimeException('not supported', 500);
        }

        /** @var Access $access */
        $access = $this->security->getUser();
        $originalAccess = null;

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

        if($token instanceof SwitchUserToken){
            /** @var Access $originalAccess */
            $originalAccess = $token->getOriginalToken()->getUser();
        }

        return $this->accessProfileCreator->getAccessProfile($access, $originalAccess);
    }
}