<?php

declare(strict_types=1);

namespace Drupal\Tests\acquia_dam\Kernel;

/**
 * Tests Acquia DAM admin menu links.
 *
 * @group acquia_dam
 */
final class AcquiaDamMenuLinksTest extends AcquiaDamKernelTestBase {

  /**
   * Tests the Acquia DAM menu links are discovered correctly.
   */
  public function testAdminMenuLinks(): void {
    $this->assertMenuLinkDefinition('acquia_dam.metadata_config', [
      'title' => 'Metadata',
      'parent' => 'acquia_dam.config',
      'weight' => 1,
    ]);

    $this->assertMenuLinkDefinition('acquia_dam.image_style_config', [
      'title' => 'Image styles',
      'parent' => 'acquia_dam.config',
      'weight' => 2,
    ]);

    $this->assertMenuLinkDefinition('acquia_dam.integration_links', [
      'title' => 'Integration links',
      'parent' => 'acquia_dam.config',
      'weight' => 3,
    ]);
  }

  /**
   * Tests the Acquia DAM Bulk Asset Import menu link is discovered correctly.
   */
  public function testAssetImportSubmoduleMenuLink(): void {
    $this->enableModules(['acquiadam_asset_import']);

    $this->assertMenuLinkDefinition('acquiadam_asset_import.configuration', [
      'title' => 'Bulk import',
      'parent' => 'acquia_dam.config',
      'weight' => 4,
    ]);
  }

  /**
   * Asserts a menu link definition exists and matches expected values.
   *
   * @param string $plugin_id
   *   The menu link plugin ID.
   * @param array<string, mixed> $expected
   *   The expected definition values.
   */
  private function assertMenuLinkDefinition(string $plugin_id, array $expected): void {
    $definition = $this->getMenuLinkDefinition($plugin_id);

    foreach ($expected as $key => $value) {
      $this->assertArrayHasKey($key, $definition);

      $actual = $definition[$key];
      if ($key === 'title' || $key === 'description') {
        $actual = (string) $actual;
      }

      $this->assertSame($value, $actual);
    }
  }

  /**
   * Gets a menu link definition by plugin ID.
   *
   * @param string $plugin_id
   *   The menu link plugin ID.
   *
   * @return array<string, mixed>
   *   The menu link definition.
   */
  private function getMenuLinkDefinition(string $plugin_id): array {
    /** @var \Drupal\Core\Menu\MenuLinkManagerInterface $menu_link_manager */
    $menu_link_manager = $this->container->get('plugin.manager.menu.link');
    $menu_link_manager->rebuild();
    $definitions = $menu_link_manager->getDefinitions();
    $this->assertNotEmpty($definitions);

    return $definitions[$plugin_id];
  }

}
