<?php

namespace Drupal\Tests\acquia_contenthub_publisher\Kernel\EventSubscriber\ExcludeContentField;

use Drupal\acquia_contenthub\Event\ExcludeEntityFieldEvent;
use Drupal\acquia_contenthub_publisher\EventSubscriber\ExcludeContentField\RemoveExcludedFields;
use Drupal\KernelTests\KernelTestBase;
use Drupal\Tests\node\Traits\ContentTypeCreationTrait;
use Drupal\Tests\node\Traits\NodeCreationTrait;

/**
 * Tests removal of excluded fields from serialization.
 *
 * @group acquia_contenthub_publisher
 * @coversDefaultClass \Drupal\acquia_contenthub_publisher\EventSubscriber\ExcludeContentField\RemoveExcludedFields
 *
 * @requires module depcalc
 *
 * @package Drupal\Tests\acquia_contenthub_publisher\Kernel\EventSubscriber\ExcludeContentField
 */
class RemoveExcludedFieldsTest extends KernelTestBase {

  use ContentTypeCreationTrait;
  use NodeCreationTrait;

  /**
   * {@inheritDoc}
   */
  protected static $modules = [
    'field',
    'filter',
    'depcalc',
    'acquia_contenthub',
    'acquia_contenthub_publisher',
    'node',
    'text',
    'user',
    'system',
  ];

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

    $this->installConfig('node');
    $this->installConfig('filter');

    $this->installEntitySchema('node');
    $this->installEntitySchema('user');
  }

  /**
   * Tests the removal of excluded fields.
   *
   * @covers ::shouldExclude
   */
  public function testRemoveExcludedFields(): void {
    $this->createContentType([
      'type' => 'article',
      'name' => 'Article',
    ]);
    $node = $this->createNode([
      'type' => 'article',
    ]);

    $excluded_fields = [
      'title',
      'body',
    ];

    /** @var \Drupal\acquia_contenthub_publisher\Libs\ExcludeSettingsInterface $exclude_settings */
    $exclude_settings = $this->container->get('acquia_contenthub_publisher.exclude.settings');
    $exclude_settings->excludeFields('node', 'article', $excluded_fields);
    $exclude_settings->save();

    $sut = new RemoveExcludedFields($exclude_settings);
    foreach ($node as $field_name => $field) {
      $event = new ExcludeEntityFieldEvent($node, $field_name, $field);
      $sut->excludeContentField($event);

      if (in_array($field_name, $excluded_fields)) {
        $this->assertTrue($event->isExcluded(), "Field {$field_name} is excluded.");
        $this->assertTrue($event->isPropagationStopped(), "Propagation is stopped for field {$field_name}.");
      }
      else {
        $this->assertFalse($event->isExcluded(), "Field {$field_name} is not excluded.");
        $this->assertFalse($event->isPropagationStopped(), "Propagation is not stopped for field {$field_name}.");
      }
    }
  }

}
