<?php
/**
 * Copyright since 2025 InPost S.A.
 *
 * For the full license information, please view the LICENSE file bundled with the module.
 *
 * @author InPost S.A.
 * @copyright since 2025 InPost S.A.
 * @license MIT
 */

declare(strict_types=1);

namespace InPost\International\Configuration\Form\Type;

use InPost\International\Configuration\Form\Type\Api\EnvironmentChoiceType;
use InPost\International\Configuration\Form\Type\Api\EnvironmentConfigurationType;
use InPost\International\Configuration\Message\UpdateApiConfigurationCommand;
use InPost\International\Environment\EnvironmentInterface;
use InPost\International\Environment\EnvironmentRegistry;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Contracts\Translation\TranslatorInterface;

if (!defined('_PS_VERSION_')) {
    exit;
}

final class ApiConfigurationType extends AbstractType
{
    /**
     * @var TranslatorInterface
     */
    private $translator;

    /**
     * @var EnvironmentRegistry
     */
    private $envRegistry;

    public function __construct(TranslatorInterface $translator, EnvironmentRegistry $envRegistry)
    {
        $this->translator = $translator;
        $this->envRegistry = $envRegistry;
    }

    /**
     * @param array{environments: EnvironmentInterface[]} $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder->add('environment', EnvironmentChoiceType::class, [
            'label' => $this->translator->trans('Active environment', [], 'Modules.Inpostinternational.Configuration'),
        ]);

        foreach ($options['environments'] as $environment) {
            $builder->add($environment->getId(), EnvironmentConfigurationType::class, [
                'environment' => $environment,
                'property_path' => sprintf('configurations[%s]', $environment->getId()),
                'required' => false,
                'label' => $environment->getName(),
            ]);
        }
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver
            ->setDefaults([
                'data_class' => UpdateApiConfigurationCommand::class,
                'environments' => null,
            ])
            ->setAllowedTypes('environments', [EnvironmentInterface::class . '[]', 'string[]', 'null'])
            ->setNormalizer('environments', function (Options $options, $value): array {
                if (null === $value || [] === $value) {
                    return $this->envRegistry->getAll();
                }

                return array_map(function ($env): EnvironmentInterface {
                    return $env instanceof EnvironmentInterface ? $env : $this->envRegistry->get($env);
                }, array_unique($value));
            });
    }
}
