<?php

declare(strict_types=1);

namespace Gls\GlsPoland\Form\DataTransformer;

use Gls\GlsPoland\Carrier\TimeDefiniteService;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;

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

        if (!$value instanceof TimeDefiniteService) {
            throw new TransformationFailedException(sprintf('Expected a %s.', TimeDefiniteService::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 TimeDefiniteService::from($value);
        } catch (\Exception $e) {
            throw new TransformationFailedException($e->getMessage(), $e->getCode(), $e);
        }
    }
}
