<?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 GroupDataImportForm's CSV upload path.
 *
 * In particular the Symfony\Component\Yaml\Yaml::parse() ->
 * Drupal\Component\Serialization\Yaml::decode() migration used to parse the
 * plugin_configuration column.
 */
#[Group('simple_interactive_maps')]
#[RunTestsInSeparateProcesses]
final class GroupDataImportFormTest extends BrowserTestBase {

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

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

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

  /**
   * Tests that CSV upload parses the YAML plugin_configuration column.
   */
  public function testCsvUploadParsesYamlPluginConfiguration(): void {
    $map = InteractiveMap::create([
      'id' => 'test_map',
      'label' => 'Test Map',
      'base_map' => 'us_states_territories',
    ]);
    $map->save();

    $path = sys_get_temp_dir() . '/groups.csv';
    $fh = fopen($path, 'w');
    fputcsv($fh, [
      'id', 'label', 'override_colors', 'fill_color', 'hover_color',
      'stroke_color', 'text_color', 'override_tooltip', 'tooltip_value',
      'tooltip_format', 'override_action', 'action_plugin_id',
      'action_configuration',
    ]);
    fputcsv($fh, [
      'group_a', 'Group A', '1', '#111111', '#222222', '#333333', '#444444',
      '0', '', 'plain_text', '1', 'navigate_action',
      "{url: 'https://example.com', new_tab: true}",
    ]);
    fclose($fh);

    $this->drupalGet('/admin/structure/interactive-map/test_map/tools/group-import');
    $this->assertSession()->statusCodeEquals(200);

    $page = $this->getSession()->getPage();
    $page->attachFileToField('files[import_group_file]', $path);
    $page->pressButton('Send');
    $this->assertSession()->pageTextContains('Group data has been imported.');

    /** @var \Drupal\simple_interactive_maps\Entity\InteractiveMap $loaded */
    $loaded = \Drupal::entityTypeManager()->getStorage('interactive_map')->loadUnchanged('test_map');
    $groups = $loaded->getGroups();

    $this->assertArrayHasKey('group_a', $groups);
    $this->assertSame('navigate_action', $groups['group_a']['action']['plugin_id']);
    $this->assertSame('https://example.com', $groups['group_a']['action']['plugin_configuration']['url']);
    $this->assertTrue($groups['group_a']['action']['plugin_configuration']['new_tab']);
  }

}
