<?php

namespace Drupal\acquia_contenthub_publisher\EventSubscriber\EnqueueEligibility;

use Drupal\acquia_contenthub_publisher\ContentHubPublisherEvents;
use Drupal\acquia_contenthub_publisher\Event\ContentHubEntityEligibilityEvent;
use Drupal\acquia_contenthub_publisher\Libs\ConfigSyndicationSettings;
use Drupal\Core\Config\Entity\ConfigEntityInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Subscribes to entity eligibility to prevent enqueueing config entities.
 */
class ExcludeConfigEntities implements EventSubscriberInterface {

  /**
   * Content Hub config entities syndication setting.
   *
   * @var \Drupal\acquia_contenthub_publisher\Libs\ConfigSyndicationSettings
   */
  protected ConfigSyndicationSettings $configSyndicationSetting;

  /**
   * ExcludeConfigEntities constructor.
   *
   * @param \Drupal\acquia_contenthub_publisher\Libs\ConfigSyndicationSettings $config_syndication_settings
   *   Content Hub config entities syndication setting.
   */
  public function __construct(ConfigSyndicationSettings $config_syndication_settings) {
    $this->configSyndicationSetting = $config_syndication_settings;
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents(): array {
    $events[ContentHubPublisherEvents::ENQUEUE_CANDIDATE_ENTITY][] =
      ['onEnqueueCandidateEntity', 50];
    return $events;
  }

  /**
   * Prevent config entities from enqueueing.
   *
   * @param \Drupal\acquia_contenthub_publisher\Event\ContentHubEntityEligibilityEvent $event
   *   The event to determine entity eligibility.
   *
   * @throws \Exception
   */
  public function onEnqueueCandidateEntity(ContentHubEntityEligibilityEvent $event): void {
    $entity = $event->getEntity();
    if ($this->configSyndicationSetting->isConfigSyndicationDisabled() && ($entity instanceof ConfigEntityInterface)) {
      $event->setEligibility(FALSE);
      $event->setReason('Config entities syndication is disabled.');
      $event->stopPropagation();
    }
  }

}
