<?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\DataTransformer;

use InPost\International\Country;
use InPost\International\PrestaShop\ObjectModel\Repository\CountryRepository;
use InPost\International\PrestaShop\ObjectModel\Repository\ObjectRepositoryInterface;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;

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

final class CountryModelToEnumCaseTransformer implements DataTransformerInterface
{
    /**
     * @var CountryRepository
     */
    private $repository;

    /**
     * @param CountryRepository $repository
     */
    public function __construct(ObjectRepositoryInterface $repository)
    {
        $this->repository = $repository;
    }

    /**
     * {@inheritDoc}
     */
    public function transform($value): ?Country
    {
        if (null === $value) {
            return null;
        }

        if (!$value instanceof \Country) {
            throw new TransformationFailedException('Expected a \Country.');
        }

        try {
            return Country::from((string) $value->iso_code);
        } catch (\Exception $e) {
            throw new TransformationFailedException('Unsupported country.', 0, $e);
        }
    }

    /**
     * {@inheritDoc}
     */
    public function reverseTransform($value): ?\Country
    {
        if (null === $value) {
            return null;
        }

        if (!$value instanceof Country) {
            throw new TransformationFailedException(sprintf('Expected an instance of "%s".', Country::class));
        }

        return $this->repository->findOneByIsoCode($value->value);
    }
}
