<?php

namespace Drupal\acquia_contenthub_subscriber\EventSubscriber\ReplaceEntityUuidWithId;

use Drupal\acquia_contenthub\Libs\Traits\ViewFilterPluginHelperTrait;
use Drupal\Component\Uuid\Uuid;

/**
 * Replaces entity id with uuid for numeric plugin filter.
 *
 * @package \Drupal\acquia_contenthub_subscriber\Event\ReplaceEntityUuidWithIdEvent
 */
class NumericViewFilterPlugin extends ViewFilterPluginReplaceEntityUuidWithIdBase {

  use ViewFilterPluginHelperTrait;

  /**
   * Replaces entity uuid with id for numeric plugin.
   *
   * @param array $filter_data
   *   The filter data.
   *
   * @return array
   *   The updated filter data.
   *
   * @throws \Exception
   */
  public function replaceEntityUuidWithIdForViewFilterPlugin(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 uuid with id.
    foreach ($filter_data['value'] as $key => $uuid) {
      if (!Uuid::isValid($uuid)) {
        continue;
      }
      $entities = $this->entityTypeManager->getStorage($entity_type)->loadByProperties(['uuid' => [$uuid]]);
      if ($entities) {
        /** @var \Drupal\Core\Entity\EntityInterface $entity */
        $entity = reset($entities);
        $filter_data['value'][$key] = $entity->id();
        continue;
      }
      $this->logMissingEntity($entity_type, $uuid, $filter_data['plugin_id']);
    }
    return $filter_data;
  }

}
