<?php

declare(strict_types=1);

namespace App\DataProvider\Access;

use ApiPlatform\Core\DataProvider\ItemDataProviderInterface;
use ApiPlatform\Core\DataProvider\RestrictedDataProviderInterface;
use App\ApiResources\Profile\AccessProfile;
use App\Entity\Access\Access;
use App\Service\Access\AccessProfileCreator;
use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
use Symfony\Component\Security\Core\Security;

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

    public function supports(string $resourceClass, string $operationName = null, array $context = []): bool
    {
        return AccessProfile::class === $resourceClass;
    }

    public function getItem(string $resourceClass, $id, string $operationName = null, array $context = []): ?AccessProfile
    {
        /** @var Access $access */
        $access = $this->security->getUser();
        $originalAccess = null;

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

        if($token instanceof SwitchUserToken){
            $originalAccess = $token->getOriginalToken()->getUser();
        }

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