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

use Chill\ThirdPartyBundle\Entity\ThirdParty;
use Chill\ThirdPartyBundle\Templating\Entity\ThirdPartyRender;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

final class ThirdPartyHasEmailValidator extends ConstraintValidator
{
    public function __construct(private readonly ThirdPartyRender $thirdPartyRender) {}

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

        if (null === $value) {
            return;
        }

        if (!$value instanceof ThirdParty) {
            throw new UnexpectedTypeException($value, ThirdParty::class);
        }

        if (null === $value->getEmail() || '' === $value->getEmail()) {
            $this->context->buildViolation($constraint->message)
                ->setParameter('{{ thirdParty }}', $this->thirdPartyRender->renderString($value, []))
                ->setCode($constraint->code)
                ->addViolation();
        }
    }
}
