<?php

declare(strict_types=1);

namespace Drupal\flowdrop_stategraph\Reducer;

/**
 * Reducer that appends values to an array.
 *
 * This reducer is designed for accumulating values over time, such as:
 * - Message history in chat workflows.
 * - Tool call logs in agent workflows.
 * - Event sequences for audit trails.
 *
 * The update value can be:
 * - A single item: Appended as one element.
 * - An array: Each element is appended individually.
 *
 * Example:
 * @code
 * $reducer = new AppendReducer();
 *
 * // Appending a single message.
 * $result = $reducer->reduce(
 *   ["Hello"],
 *   "World"
 * );
 * // Result: ["Hello", "World"]
 *
 * // Appending multiple messages.
 * $result = $reducer->reduce(
 *   ["Hello"],
 *   ["World", "!"]
 * );
 * // Result: ["Hello", "World", "!"]
 * @endcode
 *
 * @internal This class is not part of the public API and may change without notice.
 */
final class AppendReducer implements ReducerInterface {

  /**
   * {@inheritdoc}
   */
  public function getId(): string {
    return "append";
  }

  /**
   * {@inheritdoc}
   */
  public function reduce(mixed $currentValue, mixed $updateValue): mixed {
    // Ensure current value is an array.
    if (!is_array($currentValue)) {
      $currentValue = [];
    }

    // If update value is an array, append all items.
    if (is_array($updateValue)) {
      foreach ($updateValue as $item) {
        $currentValue[] = $item;
      }
    }
    else {
      // Append single item.
      $currentValue[] = $updateValue;
    }

    return $currentValue;
  }

  /**
   * {@inheritdoc}
   */
  public function getDefaultValue(): mixed {
    return [];
  }

}
