<?php

namespace Drupal\Tests\acquia_contenthub_publisher\Kernel;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Routing\RouteProviderInterface;
use Drupal\Core\Url;
use Drupal\KernelTests\KernelTestBase;

/**
 * Tests CH dynamic routes for dependency field exclusion UI.
 *
 * @group acquia_contenthub_publisher
 *
 * @requires module depcalc
 *
 * @coversDefaultClass \Drupal\acquia_contenthub_publisher\Routing\RouteSubscriber
 */
class AchRouteSubscriberTest extends KernelTestBase {

  /**
   * An entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected EntityTypeManagerInterface $entityTypeManager;

  /**
   * Route provider.
   *
   * @var \Drupal\Core\Routing\RouteProviderInterface
   */
  protected RouteProviderInterface $routeProvider;

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

  /**
   * {@inheritdoc}
   */
  protected function setUp(): void {
    parent::setUp();

    $this->entityTypeManager = $this->container->get('entity_type.manager');
    $this->routeProvider = $this->container->get('router.route_provider');
  }

  /**
   * Tests CH field exclusion route existence.
   */
  public function testContentHubExportRouteExistence(): void {
    foreach ($this->entityTypeManager->getDefinitions() as $entity_type_id => $entity_type_definition) {
      if ($entity_type_definition->get('field_ui_base_route')) {
        $route = "entity.{$entity_type_id}.contenthub_export";
        $this->assertRoute($route);
      }
    }
  }

  /**
   * Performs route related assertions.
   *
   * @param string $route
   *   The route.
   */
  protected function assertRoute(string $route): void {
    $routes = $this->routeProvider->getRoutesByNames([$route]);
    $this->assertTrue(isset($routes[$route]), 'The route exists.');

    $url = Url::fromRoute($route);
    $this->assertTrue($url->isRouted(), 'The route is properly defined and routable.');
  }

}
