<?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\Checkout\Form\Type;

use InPost\International\Checkout\Form\DataTransformer\CountryModelToEnumCaseTransformer;
use InPost\International\Checkout\Form\Model\Address;
use InPost\International\PrestaShop\ObjectModel\Form\DataTransformer\ObjectModelToIdTransformer;
use InPost\International\PrestaShop\ObjectModel\ObjectManagerInterface;
use InPost\International\PrestaShop\ObjectModel\Repository\CountryRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\DataTransformer\DataTransformerChain;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\ReversedTransformer;
use Symfony\Component\OptionsResolver\OptionsResolver;

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

final class AddressType extends AbstractType
{
    /**
     * @var ObjectManagerInterface
     */
    private $manager;

    public function __construct(ObjectManagerInterface $manager)
    {
        $this->manager = $manager;
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('address')
            ->add('postcode')
            ->add('city')
            ->add('country', IntegerType::class);

        /** @var CountryRepository $countryRepository */
        $countryRepository = $this->manager->getRepository(\Country::class);

        $builder->get('country')->addModelTransformer(new DataTransformerChain([
            new ReversedTransformer(new CountryModelToEnumCaseTransformer($countryRepository)),
            new ObjectModelToIdTransformer($this->manager, \Country::class),
        ]));
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => Address::class,
        ]);
    }
}
