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

use Chill\PersonBundle\Entity\AccompanyingPeriod;
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 LocationValidityValidator extends ConstraintValidator
{
    public function __construct(private readonly PersonRenderInterface $render) {}

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

        if (!$period instanceof AccompanyingPeriod) {
            throw new UnexpectedValueException($period, AccompanyingPeriod::class);
        }

        if ('person' === $period->getLocationStatus()) {
            if (
                null === $period->getOpenParticipationContainsPerson(
                    $period->getPersonLocation()
                )
            ) {
                $this->context->buildViolation($constraint->messagePersonLocatedMustBeAssociated)
                    ->setParameter('{{ person_name }}', $this->render->renderString(
                        $period->getPersonLocation(),
                        []
                    ))
                    ->addViolation();
            }
        }

        if (
            AccompanyingPeriod::STEP_DRAFT !== $period->getStep()
            && 'none' === $period->getLocationStatus()
        ) {
            $this->context
                ->buildViolation(
                    $constraint->messagePeriodMustRemainsLocated
                )
                ->addViolation();
        }
    }
}
