<?php

namespace Drupal\Tests\acquia_contenthub\Kernel;

use Acquia\ContentHubClient\CDF\CDFObject;
use Acquia\ContentHubClient\CDF\ClientCDFObject;
use Acquia\ContentHubClient\CDFDocument;
use Acquia\ContentHubClient\ContentHubClient;
use Acquia\ContentHubClient\Settings;
use Acquia\Hmac\Key;
use Drupal\acquia_contenthub\AcquiaContentHubEvents;
use Drupal\acquia_contenthub\Client\ClientFactory;
use Drupal\acquia_contenthub\Event\HandleWebhookEvent;
use Drupal\KernelTests\Core\Entity\EntityKernelTestBase;
use Drupal\Tests\acquia_contenthub\Traits\QueueTestTrait;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class ImportTest.
 *
 * @group acquia_contenthub
 *
 * @package Drupal\Tests\acquia_contenthub\Kernel
 */
class ImportTrackingTest extends EntityKernelTestBase {
  use QueueTestTrait;

  /**
   * {@inheritdoc}
   */
  protected static $modules = [
    'user',
    'file',
    'node',
    'field',
    'depcalc',
    'acquia_contenthub',
    'acquia_contenthub_subscriber',
    'acquia_contenthub_server_test',
  ];

  /**
   * Event dispatcher.
   *
   * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
   */
  protected $dispatcher;

  /**
   * Contenthub client factory.
   *
   * @var \Drupal\acquia_contenthub\Client\ClientFactory
   */
  protected $clientFactory;

  /**
   * Import queue instance.
   *
   * @var \Drupal\acquia_contenthub_subscriber\ContentHubImportQueue
   */
  protected $importQueue;

  /**
   * The subscriber tracker.
   *
   * @var \Drupal\acquia_contenthub_subscriber\SubscriberTracker
   */
  protected $importTracker;

  /**
   * The Content Hub Settings Object.
   *
   * @var \Acquia\ContentHubClient\Settings
   */
  protected Settings $settings;

  /**
   * Client UUID.
   *
   * @var string
   */
  protected $settingsClientUuid = '00000000-0000-460b-ac74-b6bed08b4441';

  /**
   * Initiator UUID.
   *
   * @var string
   */
  protected $initiatorID = '00000000-abba-47f1-6a54-1e485293a301';

  /**
   * {@inheritdoc}
   *
   * @throws \Exception
   */
  protected function setup(): void {
    parent::setUp();

    $this->installSchema('acquia_contenthub_subscriber', ['acquia_contenthub_subscriber_import_tracking']);

    $this->importQueue = $this->container->get('acquia_contenthub_subscriber.acquia_contenthub_import_queue');
    $this->dispatcher = $this->container->get('event_dispatcher');
    $this->importTracker = $this->container->get('acquia_contenthub_subscriber.tracker');

    $cdf_object = $this->createMock(CDFObject::class);

    $cdf_object->method('getMetadata')
      ->willReturn([]);

    $content_hub_settings = $this->createMock(Settings::class);
    $content_hub_settings
      ->method('getUuid')
      ->willReturn($this->settingsClientUuid);
    $content_hub_settings
      ->method('getWebhook')
      ->willReturn('some-uuid');
    $content_hub_settings
      ->method('toArray')
      ->willReturn([
        'webhook' => [
          'uuid' => 'some-uuid',
        ],
        'name' => 'some-client-name',
      ]);

    $content_hub_client = $this->createMock(ContentHubClient::class);
    $content_hub_client
      ->method('getSettings')
      ->willReturn($content_hub_settings);
    $content_hub_client
      ->method('getEntity')
      ->willReturn($cdf_object);

    $client_factory = $this->createMock(ClientFactory::class);
    $client_factory->method('getClient')->willReturn($content_hub_client);
    $this->clientFactory = $client_factory;
    $this->container->set('acquia_contenthub.client.factory',
      $client_factory);
    $this->ensureQueueTableExists();
  }

  /**
   * Tests adding items to queue.
   */
  public function testImportQueueOperations() {
    $this->assertEquals(0, $this->importQueue->getQueueCount(), 'By default import queue should be empty.');

    $uuid1 = '00000000-0001-460b-ac74-b6bed08b4441';
    $uuid2 = '00000000-0002-4be4-8bf0-c86d895721e9';
    // Simulate adding of 2 content entities.
    $payload = [
      'status' => 'successful',
      'crud' => 'update',
      'assets' => [
        [
          'uuid' => $uuid1,
          'type' => 'drupal8_content_entity',
        ],
        [
          'uuid' => $uuid2,
          'type' => 'drupal8_config_entity',
        ],
      ],
      'initiator' => $this->initiatorID,
    ];
    $this->invokeImportUpdateAssets($payload);
    $this->assertEquals(1, $this->importQueue->getQueueCount());
    $this->assertTrue($this->importTracker->isTracked([$uuid1, $uuid2]));
    $this->assertSame('queued', $this->importTracker->getStatusByUuid($uuid1));
    $this->assertSame('queued', $this->importTracker->getStatusByUuid($uuid2));

    // Add one more item.
    $uuid3 = '00000000-0003-460b-ac74-b6bed08b4441';
    $payload = [
      'status' => 'successful',
      'crud' => 'update',
      'assets' => [
        [
          'uuid' => $uuid3,
          'type' => 'drupal8_content_entity',
        ],
      ],
      'initiator' => $this->initiatorID,
    ];
    $this->invokeImportUpdateAssets($payload);
    $this->assertEquals(2, $this->importQueue->getQueueCount());
    $this->assertTrue($this->importTracker->isTracked([$uuid1, $uuid2, $uuid3]));
    $this->assertSame('queued', $this->importTracker->getStatusByUuid($uuid3));
  }

  /**
   * Tests wrong assets type.
   *
   * Only items with following types will be tracked:
   * - drupal8_content_entity
   * - drupal8_config_entity.
   */
  public function testTrackingWithWrongAssetType() {
    $uuid = '00000000-0003-460b-ac74-b6bed08b4441';
    $payload = [
      'status' => 'successful',
      'crud' => 'update',
      'assets' => [
        [
          'uuid' => $uuid,
          'type' => 'unknown_entity_type',
        ],
      ],
      'initiator' => $this->initiatorID,
    ];
    $this->invokeImportUpdateAssets($payload);
    $this->assertEquals(0, $this->importQueue->getQueueCount());
    $this->assertFalse($this->importTracker->isTracked([$uuid]));
  }

  /**
   * Tests tracking with empty assets.
   */
  public function testTrackingWithEmptyAssets() {
    $payload = [
      'status' => 'successful',
      'crud' => 'update',
      'assets' => [],
      'initiator' => $this->initiatorID,
    ];
    $this->invokeImportUpdateAssets($payload);
    $this->assertEquals(0, $this->importQueue->getQueueCount());
    $this->assertEmpty($this->importTracker->listTrackedEntities(['queued', 'imported']));
  }

  /**
   * Tests identical UUIDs in initiator and asset.
   *
   * We shouldn't import content in case when site is publisher and subscriber
   * at same time.
   */
  public function testTrackingWhenInitiatorAndAssetUuidIsIdentical() {
    $uuid = '00000000-0003-460b-ac74-b6bed08b4441';
    $payload = [
      'status' => 'successful',
      'crud' => 'update',
      'assets' => [
        [
          'uuid' => $uuid,
          'type' => 'drupal8_content_entity',
        ],
      ],
      'initiator' => $this->settingsClientUuid,
    ];
    $request = Request::createFromGlobals();
    $key = new Key('id', 'secret');
    $event = new HandleWebhookEvent($request, $payload, $key, $this->clientFactory->getClient());
    $this->dispatcher->dispatch($event, AcquiaContentHubEvents::HANDLE_WEBHOOK);
    $this->assertEquals(0, $this->importQueue->getQueueCount());
    $this->assertFalse($this->importTracker->isTracked([$uuid]));
  }

  /**
   * Tests tracking with wrong payload status.
   */
  public function testTrackingWithWrongPayloadStatus() {
    $payload = [
      'status' => 'any_status_except_successful',
      'crud' => 'update',
      'assets' => [],
      'initiator' => $this->initiatorID,
    ];

    $this->invokeImportUpdateAssets($payload);
    $this->assertEquals(0, $this->importQueue->getQueueCount());
    $this->assertEmpty($this->importTracker->listTrackedEntities(['queued', 'imported']));
  }

  /**
   * Triggers HANDLE_WEBHOOK event.
   *
   * @param array $payload
   *   Payload data.
   */
  protected function invokeImportUpdateAssets(array $payload) {
    $request = Request::createFromGlobals();

    $key = new Key('id', 'secret');
    $client = $this->prophesize(ContentHubClient::class);

    $this->getAcquiaContentHubAdminSettings();
    $client->getSettings()->willReturn($this->settings);

    $client_cdf = $this->prophesize(ClientCDFObject::class);
    $cdf_doc = $this->prophesize(CDFDocument::class);
    $cdf_doc->getEntities()->willReturn([$client_cdf->reveal()]);

    $client_factory = $this->prophesize(ClientFactory::class);
    $client_factory->getClient()->willReturn($client->reveal());
    $this->container->set('acquia_contenthub.client.factory', $client_factory->reveal());
    $client->getEntities(['00000000-0001-460b-ac74-b6bed08b4441', '00000000-0002-4be4-8bf0-c86d895721e9'])
      ->willReturn($cdf_doc->reveal());
    $event = new HandleWebhookEvent($request, $payload, $key, $client->reveal());
    $this->dispatcher->dispatch($event, AcquiaContentHubEvents::HANDLE_WEBHOOK);
  }

  /**
   * Get Acquia Content Hub settings.
   */
  public function getAcquiaContentHubAdminSettings(): void {
    /** @var \Drupal\acquia_contenthub\Settings\ContentHubConfigurationInterface $ch_configurations */
    $ch_configurations = $this->container->get('acquia_contenthub.configuration');
    $connection_details = $ch_configurations->getConnectionDetails();

    $connection_details->setClientName('test-client');
    $connection_details->setClientUuid('00000000-0000-0001-0000-123456789123');
    $connection_details->setApiKey('HqkhciruZhJxg6b844wc');
    $connection_details->setSecretKey('u8Pk4dTaeBWpRxA9pBvPJfru8BFSenKZi79CBKkk');
    $connection_details->setHostname('https://dev-use1.content-hub-dev.acquia.com');
    $connection_details->setSharedSecret('12312321312321');
    $ch_configurations->getContentHubConfig()->disableContentHubUpdates();
    $this->settings = $ch_configurations->getSettings();
  }

}
