<?php

namespace Drupal\Tests\acquia_contenthub\Kernel\EventSubscriber\EntityImport\FilterFormat;

use Acquia\ContentHubClient\CDFDocument;
use Drupal\acquia_contenthub_subscriber\SubscriberTracker;
use Drupal\depcalc\DependencyStack;
use Drupal\editor\Entity\Editor;
use Drupal\Tests\acquia_contenthub\Kernel\ImportExportTestBase;

/**
 * Tests filter format creation.
 *
 * @group acquia_contenthub
 *
 * @requires module depcalc
 *
 * @package Drupal\Tests\acquia_contenthub\Kernel
 */
class FilterFormatEditorTest extends ImportExportTestBase {

  /**
   * Cdf document.
   *
   * @var \Acquia\ContentHubClient\CDFDocument
   */
  protected CDFDocument $cdfDocument;

  /**
   * {@inheritdoc}
   */
  protected static $modules = [
    'editor',
    'filter',
    'system',
    'user',
    'acquia_contenthub_subscriber',
  ];

  /**
   * {@inheritDoc}
   */
  public function setUp(): void {
    parent::setUp();

    $this->installSchema('user', ['users_data']);
    $this->installSchema('acquia_contenthub_subscriber', [SubscriberTracker::IMPORT_TRACKING_TABLE]);
    $this->installEntitySchema('filter_format');
    $this->cdfDocument = $this->createCdfDocumentFromFixtureFile('node/node_ck5_formatter.json');
  }

  /**
   * Tests that editor gets created for ckeditor5 plugin.
   */
  public function testEditorCreation(): void {
    \Drupal::service('module_installer')->uninstall(['ckeditor5']);
    $this->assertFalse(\Drupal::moduleHandler()->moduleExists('ckeditor5'));

    $this->assertNull(Editor::load('ck5_formatter'));
    $cdf_serializer = $this->container->get('entity.cdf.serializer');
    $stack = new DependencyStack();
    $cdf_serializer->unserializeEntities($this->cdfDocument, $stack);

    $this->assertTrue(\Drupal::moduleHandler()->moduleExists('ckeditor5'));
    $editor = Editor::load('ck5_formatter');
    $this->assertNotNull($editor, 'Filter formatter created on subscriber.');
    $this->assertEquals('ckeditor5', $editor->getEditor());
  }

}
