<?php

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

use Drupal\acquia_contenthub_publisher\EventSubscriber\FilterFields\RemoveExcludedFieldsDependencies;
use Drupal\depcalc\Event\FilterDependencyCalculationFieldsEvent;
use Drupal\KernelTests\KernelTestBase;
use Drupal\Tests\node\Traits\NodeCreationTrait;

/**
 * Tests the removal of excluded fields from dependencies.
 *
 * @group acquia_contenthub_publisher
 * @coversDefaultClass \Drupal\acquia_contenthub_publisher\EventSubscriber\FilterFields\RemoveExcludedFieldsDependencies
 *
 * @requires module depcalc
 *
 * @package Drupal\Tests\acquia_contenthub_publisher\Kernel\EventSubscriber\FilterFields
 */
class RemoveExcludedFieldsDependenciesTest extends KernelTestBase {

  use NodeCreationTrait;

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

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

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

  /**
   * Tests the removal of excluded fields.
   *
   * @covers ::onFilterFields
   */
  public function testRemoveExcludedFieldsDependencies(): void {
    $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 RemoveExcludedFieldsDependencies($exclude_settings);
    $fields = $node->getFields();
    $event = new FilterDependencyCalculationFieldsEvent($node, ...$fields);
    $sut->onFilterFields($event);

    foreach ($excluded_fields as $excluded_field) {
      $this->assertNotContains($excluded_field, $event->getFields(), 'Excluded field is not present in the fields list.');
    }

    $expected_fields = array_filter($fields, function ($field) use ($excluded_fields) {
      return !in_array($field->getName(), $excluded_fields);
    });
    $this->assertEquals($expected_fields, $event->getFields(), 'Excluded fields are removed from the fields list.');
  }

}
