<?php
declare(strict_types=1);

namespace App\State\Provider\Enum;

use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\ApiResources\Enum\Enum;
use App\Service\Utils\Parser\YamlParser;
use App\Service\Utils\Reflection;
use Exception;
use RuntimeException;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Class EnumProvider : custom provider pour assurer l'alimentation des enums
 * @package App\DataProvider\Access
 */
final class EnumProvider implements ProviderInterface
{
    public function __construct(
        private Reflection $reflection,
        private readonly ParameterBagInterface $parameterBag
    )
    { }

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

        $name = $uriVariables['name'];
        $enums = $this->parameterBag->get('opentalent.enum');
        $enumClass = $enums[$name];

        if(!$enumClass) {
            throw new NotFoundHttpException(sprintf('Enum %s does\'nt exist', $name));
        }

        try{
            $items = $this->reflection->dynamicInvokeClassWithArgsAndMethod(
                $enumClass,
                'toArray'
            );
        }catch (Exception){
            throw new NotFoundHttpException(sprintf('Enum %s does\'nt exist', $name));
        }

        $enumResponse = new Enum();
        $enumResponse->setName($name);
        $enumResponse->setItems($items);
        return $enumResponse;
    }
}
