<?php

namespace Drupal\siteimprove_accessibility\Plugin\Validation\Constraint;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\taxonomy\TermInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Validates the UniqueTermNameConstraint constraint.
 */
class UniqueTermNameConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected EntityTypeManagerInterface $entityTypeManager;

  /**
   * Constructs a new UniqueTermNamePerVocabularyConstraintValidator.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function validate($value, Constraint $constraint): void {
    if (!$value) {
      return;
    }

    $term = $this->context->getRoot()->getValue();

    if (!$term instanceof TermInterface || $term->bundle() !== 'siteimprove_accessibility_rules') {
      return;
    }

    $query = $this->entityTypeManager->getStorage('taxonomy_term')->getQuery()
      ->condition('vid', 'siteimprove_accessibility_rules')
      ->condition('name', $value->label())
      ->range(0, 1)
      ->accessCheck(FALSE);

    if (!$term->isNew()) {
      $query->condition('tid', $term->id(), '<>');
    }

    if (!empty($query->execute())) {
      $this->context->addViolation($constraint->message, ['%name' => $value->label()]);
    }
  }

}
