<?php

namespace Drupal\acquia_contenthub_publisher\EventSubscriber\ReplaceEntityIdWithUuid;

use Drupal\acquia_contenthub\Libs\Traits\ViewFilterPluginHelperTrait;

/**
 * Replaces entity id with uuid for numeric filter plugin.
 *
 * @see \Drupal\acquia_contenthub_subscriber\EventSubscriber\ReplaceEntityUuidWithId\NumericViewFilterPlugin
 *   The unserializer for this plugin.
 *
 * @package \Drupal\acquia_contenthub_publisher\Event\ReplaceEntityIdWithUuidEvent
 */
class NumericViewFilterPlugin extends ViewFilterPluginReplaceEntityIdWithUuidBase {

  use ViewFilterPluginHelperTrait;

  /**
   * Replaces entity id with uuid for numeric plugin.
   *
   * @param array $filter_data
   *   The filter data.
   *
   * @return array
   *   The updated filter data.
   *
   * @throws \Exception
   */
  public function replaceEntityIdWithUuidForViewFilterPlugin(array $filter_data): array {
    if ($filter_data['plugin_id'] !== 'numeric') {
      return [];
    }
    $entity_type = $this->getTargetEntityReferenceTypeIdFromTableName($filter_data['table']);
    if (empty($entity_type)) {
      return [];
    }
    // Updating entity id with uuid.
    foreach ($filter_data['value'] as $key => $entity_id) {
      if (empty($entity_id)) {
        continue;
      }
      $entity = $this->entityTypeManager->getStorage($entity_type)->load($entity_id);
      if ($entity) {
        $filter_data['value'][$key] = $entity->uuid();
        continue;
      }
      $this->logMissingEntity($entity_type, $entity_id, $filter_data['plugin_id']);
    }
    return $filter_data;
  }

}
