<?php

namespace AutoAdmin\Bundle\Menu\Form;

use AutoAdmin\Bundle\Menu\Validator\ValidJson;
use AutoAdmin\Bundle\Seo\Form\JsonTextareaType;
use Symfony\Component\Form\CallbackTransformer;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class JsonType extends JsonTextareaType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder->addModelTransformer(
            new CallbackTransformer(
                function ($value) {
                    if (empty($value)) {
                        return '';
                    }

                    return json_encode($value, JSON_PRETTY_PRINT);
                },
                function ($value) {
                    if (empty($value)) {
                        return null;
                    }

                    $decoded = json_decode($value, true);
                    if (json_last_error() !== JSON_ERROR_NONE) {
                        return ['error' => json_last_error_msg()];
                    }

                    return $decoded;
                }
            )
        );
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'constraints' => [new ValidJson()],
        ]);
    }
}
