<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\PersonBundle\PersonIdentifier\Identifier;

use Chill\PersonBundle\Entity\Identifier\PersonIdentifier;
use Chill\PersonBundle\Entity\Identifier\PersonIdentifierDefinition;
use Chill\PersonBundle\PersonIdentifier\IdentifierViolationDTO;
use Chill\PersonBundle\PersonIdentifier\PersonIdentifierEngineInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;

final readonly class StringIdentifier implements PersonIdentifierEngineInterface
{
    public const NAME = 'chill-person-bundle.string-identifier';

    private const ONLY_NUMBERS = 'only_numbers';
    private const FIXED_LENGTH = 'fixed_length';

    public static function getName(): string
    {
        return self::NAME;
    }

    public function canonicalizeValue(array $value, PersonIdentifierDefinition $definition): ?string
    {
        return trim($value['content'] ?? '');
    }

    public function buildForm(FormBuilderInterface $builder, PersonIdentifierDefinition $personIdentifierDefinition): void
    {
        $builder->add('content', TextType::class, ['label' => false]);
    }

    public function renderAsString(?PersonIdentifier $identifier, PersonIdentifierDefinition $definition): string
    {
        return trim($identifier?->getValue()['content'] ?? '');
    }

    public function isEmpty(PersonIdentifier $identifier): bool
    {
        return '' === trim($identifier->getValue()['content'] ?? '');
    }

    public function validate(PersonIdentifier $identifier, PersonIdentifierDefinition $definition): array
    {
        $config = $definition->getData();
        $content = (string) ($identifier->getValue()['content'] ?? '');
        $violations = [];

        if (($config[self::ONLY_NUMBERS] ?? false) && !preg_match('/^[0-9]+$/', $content)) {
            $violations[] = new IdentifierViolationDTO('person_identifier.only_number', '2a3352c0-a2b9-11f0-a767-b7a3f80e52f1');
        }

        if (null !== ($config[self::FIXED_LENGTH] ?? null) && strlen($content) !== $config[self::FIXED_LENGTH]) {
            $violations[] = new IdentifierViolationDTO(
                'person_identifier.fixed_length',
                '2b02a8fe-a2b9-11f0-bfe5-033300972783',
                ['limit' => (string) $config[self::FIXED_LENGTH]]
            );
        }

        return $violations;
    }

    public function getDefaultValue(PersonIdentifierDefinition $definition): array
    {
        return ['content' => ''];
    }
}
