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

use Chill\TicketBundle\Action\Ticket\SetPersonsCommand;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedValueException;

class SetPersonCommandConstraintValidator extends ConstraintValidator
{
    private readonly bool $isMulti;

    public function __construct(ParameterBagInterface $parameterBag)
    {
        $this->isMulti = 'multi' === $parameterBag->get('chill_ticket')['ticket']['person_per_ticket'];
    }

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

        if (!$constraint instanceof SetPersonCommandConstraint) {
            throw new UnexpectedValueException($constraint, SetPersonCommandConstraint::class);
        }

        if (!$this->isMulti) {
            if (1 < count($value->persons)) {
                $this->context->buildViolation($constraint->notMulti)
                    ->atPath('persons')
                    ->addViolation();
            }
        }
    }
}
