<?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\Repository\Identifier\PersonIdentifierRepository;
use Chill\PersonBundle\Templating\Entity\PersonRenderInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Exception\UnexpectedValueException;

class UniqueIdentifierConstraintValidator extends ConstraintValidator
{
    public function __construct(
        private readonly PersonIdentifierRepository $personIdentifierRepository,
        private readonly PersonRenderInterface $personRender,
    ) {}

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

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

        $identifiers = $this->personIdentifierRepository->findByDefinitionAndCanonical($value->getDefinition(), $value->getValue());

        if (count($identifiers) > 0) {
            if (count($identifiers) > 1 || $identifiers[0]->getPerson() !== $value->getPerson()) {
                $persons = array_map(fn (PersonIdentifier $idf): string => $this->personRender->renderString($idf->getPerson(), []), $identifiers);

                $this->context->buildViolation($constraint->message)
                    ->setParameter('{{ persons }}', implode(', ', $persons))
                    ->setParameter('definition_id', (string) $value->getDefinition()->getId())
                    ->addViolation();

            }
        }
    }
}
