<?php
declare(strict_types=1);

namespace App\Validator\Organization\Parameters;

use App\Entity\Organization\Parameters;
use App\Service\Mobyt\MobytService;
use Exception;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Classe control que les logins/mot de passe mobyt sont OK.
 */
class MobytCredentialsValidator extends ConstraintValidator
{
    public function __construct(private readonly MobytService $mobytService){}

    public function validate(mixed $value, Constraint $constraint): bool
    {
        /** @var Parameters $parameters */
        $parameters = $value;

        $userNameSms = $parameters->getUsernameSMS();
        $passwordSms = $parameters->getPasswordSMS();

        if(empty($userNameSms) || empty($passwordSms)) {
            return true;
        }

        try{
            return $this->mobytService->hasCredentialsCorrect($userNameSms, $passwordSms);
        }catch (Exception){
            $this->context->buildViolation($constraint->payload)
                ->atPath('passwordSMS')
                ->addViolation();
            return false;
        }
    }
}
