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

use Chill\MainBundle\Phonenumber\PhoneNumberHelperInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * @deprecated use https://github.com/odolbeau/phone-number-bundle/blob/master/src/Validator/Constraints/PhoneNumberValidator.php instead
 */
final class ValidPhonenumber extends ConstraintValidator
{
    public function __construct(private readonly LoggerInterface $logger, private readonly PhoneNumberHelperInterface $phonenumberHelper) {}

    /**
     * @param string                                                        $value
     * @param \Chill\MainBundle\Validation\Constraint\PhonenumberConstraint $constraint
     */
    public function validate($value, Constraint $constraint)
    {
        if (false === $this->phonenumberHelper->isPhonenumberValidationConfigured()) {
            $this->logger->debug('[phonenumber] skipping validation due to not configured helper');

            return;
        }

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

        switch ($constraint->type) {
            case 'landline':
                $isValid = $this->phonenumberHelper->isValidPhonenumberLandOrVoip($value);
                $message = $constraint->notLandlineMessage;

                break;

            case 'mobile':
                $isValid = $this->phonenumberHelper->isValidPhonenumberMobile($value);
                $message = $constraint->notMobileMessage;

                break;

            case 'any':
                $isValid = $this->phonenumberHelper->isValidPhonenumberAny($value);
                $message = $constraint->notValidMessage;

                break;

            default:
                throw new \LogicException(sprintf("This type '%s' is not implemented. Possible values are 'mobile', 'landline' or 'any'", $constraint->type));
        }

        if (false === $isValid) {
            $this->context->addViolation($message, ['%phonenumber%' => $value, '%formatted%' => $this->phonenumberHelper->format($value)]);
        }
    }
}
