<?php

declare(strict_types=1);

namespace Gls\GlsPoland\Form\DataTransformer;

use Gls\GlsPoland\AdePlus\Printout\PickupReceiptPrintMode;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;

final class PickupReceiptPrintModeDataTransformer implements DataTransformerInterface
{
    public function transform($value): ?string
    {
        if (null === $value) {
            return null;
        }

        if (!$value instanceof PickupReceiptPrintMode) {
            throw new TransformationFailedException(sprintf('Expected a %s.', PickupReceiptPrintMode::class));
        }

        return (string) $value;
    }

    public function reverseTransform($value)
    {
        if (null === $value) {
            return null;
        }

        if (!is_string($value)) {
            throw new TransformationFailedException('Expected a string.');
        }

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