<?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 Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Class EnumProvider : custom provider pour assurer l'alimentation des enums.
 */
final class EnumProvider implements ProviderInterface
{
    public function __construct(
        private readonly ParameterBagInterface $parameterBag,
    ) {
    }

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

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

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

        $enumResponse = new Enum();
        $enumResponse->setName($name);
        $enumResponse->setItems($enumClass::array());

        return $enumResponse;
    }
}
