<?php

declare(strict_types=1);

namespace Drupal\Tests\simple_interactive_maps\Functional;

use Drupal\simple_interactive_maps\Entity\InteractiveMap;
use Drupal\Tests\BrowserTestBase;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses;

/**
 * Regression guard for EditorDialogForm's entity-storage refactor.
 *
 * Storage is now fetched from EntityTypeManagerInterface at each call site
 * instead of being cached as a class property populated only in the
 * constructor.
 */
#[Group('simple_interactive_maps')]
#[RunTestsInSeparateProcesses]
final class EditorDialogFormTest extends BrowserTestBase {

  /**
   * {@inheritdoc}
   */
  protected $defaultTheme = 'stark';

  /**
   * {@inheritdoc}
   */
  protected static $modules = [
    'editor',
    'file',
    'field_group',
    'simple_interactive_maps',
  ];

  /**
   * {@inheritdoc}
   */
  protected function setUp(): void {
    parent::setUp();
    $account = $this->drupalCreateUser(['administer interactive_map']);
    $this->drupalLogin($account);
  }

  /**
   * Tests that the dialog lists existing maps.
   */
  public function testDialogListsExistingMaps(): void {
    InteractiveMap::create([
      'id' => 'test_map',
      'label' => 'My Alphabetically First Map',
      'base_map' => 'us_states_territories',
    ])->save();

    $this->drupalGet('/admin/simple-interactive-maps/editor-dialog');
    $this->assertSession()->statusCodeEquals(200);
    $this->assertSession()->optionExists('map', 'test_map');
    $this->assertSession()->pageTextContains('My Alphabetically First Map');
  }

  /**
   * Tests that submitting the dialog returns an AJAX response.
   */
  public function testSubmittingTheDialogReturnsAnAjaxResponse(): void {
    InteractiveMap::create([
      'id' => 'test_map',
      'label' => 'Test Map',
      'base_map' => 'us_states_territories',
    ])->save();

    $this->drupalGet('/admin/simple-interactive-maps/editor-dialog');

    $page = $this->getSession()->getPage();
    $page->selectFieldOption('map', 'test_map');
    $page->pressButton('Embed map');

    // A successful AJAX response replaces the page with the same form
    // (no fatal error, no access-denied redirect).
    $this->assertSession()->statusCodeEquals(200);
  }

}
