<?php

namespace Drupal\Tests\acquia_contenthub_publisher\Unit\EventSubscriber\ReplaceEntityIdWithUuid;

use Drupal\acquia_contenthub_publisher\Event\ViewFilterPluginReplaceEntityIdWithUuidEvent;
use Drupal\acquia_contenthub_publisher\EventSubscriber\ReplaceEntityIdWithUuid\TaxonomyIndexIdViewFilterPlugin;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Logger\RfcLogLevel;
use Drupal\Tests\acquia_contenthub\Unit\Helpers\LoggerMock;
use Drupal\Tests\UnitTestCase;

/**
 * Tests replacing entity id with uuid for TaxonomyIndexIdViewFilterPlugin.
 *
 * @group acquia_contenthub_publisher
 *
 * @package Drupal\Tests\acquia_contenthub_publisher\Unit\EventSubscriber\ReplaceEntityIdWithUuid
 *
 * @coversDefaultClass \Drupal\acquia_contenthub_publisher\EventSubscriber\ReplaceEntityIdWithUuid\TaxonomyIndexIdViewFilterPlugin
 */
class TaxonomyIndexIdViewFilterPluginTest extends UnitTestCase {

  /**
   * Test replacing entity id with uuid for TaxonomyIndexIdViewFilterPlugin.
   *
   * @covers ::replaceEntityIdWithUuidForViewFilterPlugin
   */
  public function testTaxonomyIndexIdFilterPlugin() {
    $entity = $this->prophesize(EntityInterface::class);
    $entity->uuid()->willReturn('random-uuid');
    $entity_storage = $this->prophesize(EntityStorageInterface::class);
    $entity_storage->load(20)->willReturn($entity->reveal());
    $entity_storage->load(30)->willReturn(NULL);
    $entity_type_manager = $this->prophesize(EntityTypeManagerInterface::class);
    $entity_type_manager->getStorage('taxonomy_term')->willReturn($entity_storage);
    $filter_data = [
      'table' => 'node__field_tags',
      'plugin_id' => 'taxonomy_index_tid',
      'value' => [20, 30],
    ];
    $plugin_id = 'taxonomy_index_tid';

    $event = new ViewFilterPluginReplaceEntityIdWithUuidEvent($filter_data, $plugin_id);
    $logger = new LoggerMock();
    $event_subscriber = new TaxonomyIndexIdViewFilterPlugin($entity_type_manager->reveal(), $logger);
    $event_subscriber->onReplaceEntityIdWithUuid($event);

    $expected_filter_data = [
      'table' => 'node__field_tags',
      'plugin_id' => 'taxonomy_index_tid',
      'value' => ['random-uuid', 30],
    ];
    $this->assertSame($expected_filter_data, $event->getFilterData());
    $log_messages = $logger->getLogMessages();
    $this->assertNotEmpty($log_messages);
    $this->assertEquals(
      'Entity of type: taxonomy_term and id: 30 not found while serialization of taxonomy_index_tid view filter plugin.',
      $log_messages[RfcLogLevel::WARNING][0]
    );
  }

}
