<?php

namespace Drupal\acquia_contenthub_subscriber\Libs\PullSyndication;

use Drupal\acquia_contenthub\Client\ClientFactory;
use Drupal\acquia_contenthub\Libs\Common\EnsureContentHubClientTrait;
use Drupal\acquia_contenthub\Libs\ServiceQueue\QueueItem;
use Drupal\acquia_contenthub\Libs\ServiceQueue\QueueItemActionInterface;
use Drupal\acquia_contenthub\Libs\ServiceQueue\ServiceQueueEntityActions;
use Drupal\acquia_contenthub\Settings\ContentHubConfigurationInterface;
use Drupal\acquia_contenthub_subscriber\EntityDeletionHandlerBase;
use Drupal\acquia_contenthub_subscriber\Libs\UserDeletionHandlerInterface;
use Drupal\acquia_contenthub_subscriber\SubscriberTracker;
use Drupal\Core\DependencyInjection\DependencySerializationTrait;

/**
 * Action for deleting entities.
 *
 * Handles entity deletion operations during pull syndication.
 *
 * @internal
 * @package Drupal\acquia_contenthub_subscriber\Libs\PullSyndication
 */
class EntityDeleteAction extends EntityDeletionHandlerBase implements QueueItemActionInterface {

  use EnsureContentHubClientTrait;
  use DependencySerializationTrait;

  /**
   * Constructs a new object.
   *
   * @param \Drupal\acquia_contenthub_subscriber\SubscriberTracker $tracker
   *   The subscription tracker.
   * @param \Drupal\acquia_contenthub\Settings\ContentHubConfigurationInterface $ch_configuration
   *   CH Configurations.
   * @param \Drupal\acquia_contenthub_subscriber\Libs\UserDeletionHandlerInterface $handler
   *   The user deletion handler service.
   * @param \Drupal\acquia_contenthub\Client\ClientFactory $client_factory
   *   The Content Hub Client factory service.
   */
  public function __construct(SubscriberTracker $tracker, ContentHubConfigurationInterface $ch_configuration, UserDeletionHandlerInterface $handler, ClientFactory $client_factory) {
    parent::__construct($tracker, $ch_configuration, $handler);

    $this->clientFactory = $client_factory;
  }

  /**
   * {@inheritdoc}
   */
  public function execute(array $queue_items): void {
    $entity_uuids = [];
    $entity_uuids_to_cleanup = [];
    foreach ($queue_items as $queue_item) {
      if (!$this->isSupportedType($queue_item->getCdfType())) {
        continue;
      }
      $entity_uuids[] = $queue_item->getEntityUuid();
    }

    $this->processMultipleEntityDeletions($entity_uuids, $entity_uuids_to_cleanup);
    $this->cleanupMissingEntities($entity_uuids_to_cleanup, $this->getClient());
  }

  /**
   * {@inheritdoc}
   */
  public function canHandle(QueueItem $queue_item): bool {
    return $queue_item->isAction(ServiceQueueEntityActions::DELETE);
  }

}
