<?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\Entity\RoleScope;
use Chill\MainBundle\Security\RoleProvider;
use Chill\MainBundle\Validation\Constraint\RoleScopeScopePresenceConstraint;
use Psr\Log\LoggerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Contracts\Translation\TranslatorInterface;

class RoleScopeScopePresence extends ConstraintValidator
{
    public function __construct(private readonly RoleProvider $roleProvider, private readonly LoggerInterface $logger, private readonly TranslatorInterface $translator) {}

    public function validate($value, Constraint $constraint)
    {
        if (!$value instanceof RoleScope) {
            throw new \RuntimeException('The validated object is not an instance of roleScope');
        }

        if (!$constraint instanceof RoleScopeScopePresenceConstraint) {
            throw new \RuntimeException('This validator should be used with RoleScopScopePresenceConstraint');
        }

        $this->logger->debug('begin validation of a role scope instance');

        // if the role scope should have a scope
        if (
            !\in_array($value->getRole(), $this->roleProvider->getRolesWithoutScopes(), true)
            && null === $value->getScope()
        ) {
            $this->context->buildViolation($constraint->messagePresenceRequired)
                ->setParameter('%role%', $this->translator->trans($value->getRole()))
                ->addViolation();
            $this->logger->debug('the role scope should have a scope, but scope is null. Violation build.');
        } elseif // if the scope should be null
        (
            \in_array($value->getRole(), $this->roleProvider->getRolesWithoutScopes(), true)
            && null !== $value->getScope()
        ) {
            $this->context->buildViolation($constraint->messageNullRequired)
                ->setParameter('%role%', $this->translator->trans($value->getRole()))
                ->addViolation();
            $this->logger->debug('the role scole should not have a scope, but scope is not null. Violation build.');
        } // everything is fine !
        else {
            $this->logger->debug('role scope is valid. Validation finished.');
        }
    }
}
