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

use InPost\International\Enum\Enum;
use InPost\International\Enum\IntEnum;
use InPost\International\Enum\StringEnum;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;

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

final class EnumToValueDataTransformer implements DataTransformerInterface
{
    /**
     * @var string
     */
    private $className;

    /**
     * @param class-string<StringEnum|IntEnum> $className
     */
    public function __construct(string $className)
    {
        $this->className = $className;
    }

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

        if (!$value instanceof Enum) {
            throw new TransformationFailedException('Expected an enum.');
        }

        return $value->value;
    }

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

        if (!is_string($value) && !is_int($value)) {
            throw new TransformationFailedException('Expected a string or an integer.');
        }

        /** @var class-string<StringEnum|IntEnum> $class */
        $class = $this->className;

        try {
            return $class::from($value);
        } catch (\Exception $e) {
            throw new TransformationFailedException($e->getMessage(), $e->getCode(), $e);
        }
    }
}
