<?php

namespace Drupal\Tests\acquia_contenthub_subscriber\Unit\EventSubscriber\ReplaceEntityUuidWithId;

use Drupal\acquia_contenthub_subscriber\Event\ViewFilterPluginReplaceEntityUuidWithIdEvent;
use Drupal\acquia_contenthub_subscriber\EventSubscriber\ReplaceEntityUuidWithId\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\Traits\CommonRandomGenerator;
use Drupal\Tests\acquia_contenthub\Unit\Helpers\LoggerMock;
use Drupal\Tests\UnitTestCase;

/**
 * Tests to replace entity uuid with id for TaxonomyIndexIdViewFilterPlugin.
 *
 * @group acquia_contenthub_subscriber
 *
 * @package Drupal\Tests\acquia_contenthub_subscriber\Unit\EventSubscriber\ReplaceEntityUuidWithId
 *
 * @coversDefaultClass \Drupal\acquia_contenthub_subscriber\EventSubscriber\ReplaceEntityUuidWithId\TaxonomyIndexIdViewFilterPlugin
 */
class TaxonomyIndexIdViewFilterPluginTest extends UnitTestCase {

  use CommonRandomGenerator;

  /**
   * Test to replace entity uuid with id for TaxonomyIndexIdViewFilterPlugin.
   *
   * @covers ::replaceEntityUuidWithIdForViewFilterPlugin
   */
  public function testTaxonomyIndexIdFilterPlugin() {
    $uuid1 = $this->generateUuid();
    $uuid2 = $this->generateUuid();
    $entity = $this->prophesize(EntityInterface::class);
    $entity->id()->willReturn(20);
    $entity_storage = $this->prophesize(EntityStorageInterface::class);
    $entity_storage->loadByProperties(['uuid' => [$uuid1]])->willReturn([$entity->reveal()]);
    $entity_storage->loadByProperties(['uuid' => [$uuid2]])->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' => [$uuid1, $uuid2],
    ];
    $plugin_id = 'taxonomy_index_tid';

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

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

}
