<?php

namespace Drupal\Tests\acquia_contenthub\Kernel;

use Acquia\ContentHubClient\CDFDocument;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\depcalc\DependencyStack;
use Drupal\KernelTests\KernelTestBase;

/**
 * Tests entity cdf serializer for handleModules().
 *
 * @package acquia_contenthub
 */
class EntityCdfSerializerCacheInvalidationTest extends KernelTestBase {

  /**
   * {@inheritdoc}
   */
  protected static $modules = [
    'acquia_contenthub',
    'depcalc',
    'user',
    'system',
  ];

  /**
   * Cache default mock.
   *
   * @var \Drupal\Core\Cache\CacheBackendInterface|\Prophecy\Prophecy\ObjectProphecy
   */
  protected $cacheDefault;

  /**
   * Entity type manager mock.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface|\Prophecy\Prophecy\ObjectProphecy
   */
  protected $entityTypeManager;

  /**
   * {@inheritDoc}
   */
  public function setUp(): void {
    parent::setUp();
    $this->cacheDefault = $this->prophesize(CacheBackendInterface::class);
    $this->container->set('cache.default', $this->cacheDefault->reveal());
    $this->entityTypeManager = $this->prophesize(EntityTypeManagerInterface::class);
    $this->container->set('entity_type.manager', $this->entityTypeManager->reveal());
  }

  /**
   * Tests that cache is not cleared.
   *
   * When there are no modules to install.
   *
   * @covers \Drupal\acquia_contenthub\EntityCdfSerializer::handleModules
   *
   * @throws \ReflectionException
   */
  public function testCacheNotInvalidatedIfNewModulesNotInstalled(): void {
    $this->cacheDefault
      ->invalidateAll()
      ->shouldNotBeCalled();
    $this->entityTypeManager
      ->clearCachedDefinitions()
      ->shouldNotBeCalled();
    /** @var \Drupal\acquia_contenthub\EntityCdfSerializer $entity_cdf_serializer */
    $entity_cdf_serializer = $this->container->get('entity.cdf.serializer');
    $method_reflection = new \ReflectionMethod($entity_cdf_serializer, 'handleModules');
    $method_reflection->setAccessible(TRUE);
    $method_reflection->invoke($entity_cdf_serializer, new CDFDocument(), new DependencyStack());
  }

}
