<?php

namespace Drupal\Tests\ai_automators\Kernel;

use Drupal\KernelTests\KernelTestBase;
use Drupal\ai_automators\PluginBaseClasses\RuleBase;

/**
 * Regression tests for RuleBase::decodeValueArray().
 *
 * @group ai_automators
 */
class RuleBaseDecodeValueArrayTest extends KernelTestBase {

  /**
   * Modules to enable before running the tests.
   *
   * @var array
   */
  protected static $modules = ['system', 'file', 'user', 'ai', 'token', 'ai_automators'];

  /**
   * Ensures fallback array decoding returns all entries.
   */
  public function testDecodeValueArrayReturnsAllFallbackValues() {
    $rule = $this->container
      ->get('plugin.manager.ai_automator')
      ->createInstance('llm_list_string');
    $this->assertInstanceOf(RuleBase::class, $rule);

    $this->assertSame(
      ['alpha', 'beta', 'gamma'],
      $rule->decodeValueArray([
        ['first' => 'alpha'],
        ['second' => 'beta'],
        ['third' => 'gamma'],
      ])
    );
  }

  /**
   * Array-valued "value" key decodes identically to one object per scalar.
   *
   * Models occasionally nest all values inside a single array-valued "value"
   * key. Without flattening, the result is [["A","B"]] — a list-of-lists that
   * verifyValue() cannot match against scalar term names, leaving the field
   * empty even though every term is valid.
   */
  public function testDecodeValueArrayFlattensArrayValue() {
    $rule = $this->container
      ->get('plugin.manager.ai_automator')
      ->createInstance('llm_list_string');

    $nested = $rule->decodeValueArray([
      ['value' => ['alpha', 'beta', 'gamma']],
    ]);
    $flat = $rule->decodeValueArray([
      ['value' => 'alpha'],
      ['value' => 'beta'],
      ['value' => 'gamma'],
    ]);

    $this->assertSame(
      ['alpha', 'beta', 'gamma'],
      $nested,
      'Array-valued "value" key should be flattened to a list of scalars.',
    );
    $this->assertSame($flat, $nested, 'Nested and flat shapes must decode identically.');
  }

}
