<?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\Validator;

use Chill\PersonBundle\Entity\Identifier\PersonIdentifier;
use Chill\PersonBundle\PersonIdentifier\PersonIdentifierManagerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Exception\UnexpectedValueException;

final class ValidIdentifierConstraintValidator extends ConstraintValidator
{
    public function __construct(private readonly PersonIdentifierManagerInterface $personIdentifierManager) {}

    public function validate($value, Constraint $constraint): void
    {
        if (!$constraint instanceof ValidIdentifierConstraint) {
            throw new UnexpectedTypeException($constraint, ValidIdentifierConstraint::class);
        }

        if (!$value instanceof PersonIdentifier) {
            throw new UnexpectedValueException($value, PersonIdentifier::class);
        }

        $worker = $this->personIdentifierManager->buildWorkerByPersonIdentifierDefinition($value->getDefinition());

        $violations = $worker->validate($value, $value->getDefinition());

        foreach ($violations as $violation) {
            $this->context->buildViolation($violation->message)
                ->setParameters($violation->parameters)
                ->setParameter('{{ code }}', $violation->code)
                ->setParameter('definition_id', (string) $value->getDefinition()->getId())
                ->addViolation();
        }
    }
}
