<?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;
use App\Service\Utils\Reflection;
use Exception;
use RuntimeException;
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 Parser $parser,
        private string $opentalentConfig,
        private Reflection $reflection
    )
    { }

    /**
     * @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);
        }

        $id = $uriVariables['id'];
        $enums = $this->parser->yamlParser($this->opentalentConfig, 'enum.yaml');
        $enumClass = $enums['opentalent'][$id];

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

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

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