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

use Chill\MainBundle\Security\Resolver\CenterResolverManagerInterface;
use Chill\PersonBundle\Entity\Person;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

class PersonHasCenterValidator extends ConstraintValidator
{
    private readonly bool $centerRequired;

    public function __construct(ParameterBagInterface $parameterBag, private readonly CenterResolverManagerInterface $centerResolverManager)
    {
        $this->centerRequired = $parameterBag->get('chill_person')['validation']['center_required'];
    }

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

        if (!$this->centerRequired) {
            return;
        }

        if ([] === $this->centerResolverManager->resolveCenters($person)) {
            $this
                ->context
                ->buildViolation($constraint->message)
                ->atPath('center')
                ->addViolation();
        }
    }
}
