<?php

declare(strict_types=1);

namespace Drupal\flowdrop_runtime\Service\Storage;

use Drupal\flowdrop_pipeline\Entity\FlowDropPipelineInterface;

/**
 * In-memory implementation of pipeline storage.
 *
 * This implementation stores pipelines in PHP arrays for fast, ephemeral
 * storage. Data is not persisted beyond the current request.
 *
 * Ideal for:
 * - SynchronousOrchestrator (fast execution without DB overhead)
 * - Unit testing (fast, isolated tests)
 *
 * @internal This class is not part of the public API and may change without notice.
 */
class InMemoryPipelineStorage implements PipelineStorageInterface {

  /**
   * In-memory storage for pipelines.
   *
   * @var \Drupal\flowdrop_pipeline\Entity\FlowDropPipelineInterface[]
   */
  protected array $pipelines = [];

  /**
   * {@inheritdoc}
   */
  public function create(array $data): FlowDropPipelineInterface {
    $pipeline = new InMemoryPipeline($data);
    return $pipeline;
  }

  /**
   * {@inheritdoc}
   */
  public function load(string|int $id): ?FlowDropPipelineInterface {
    return $this->pipelines[$id] ?? NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function save(FlowDropPipelineInterface $pipeline): void {
    $id = $pipeline->id();
    if ($id !== NULL) {
      $this->pipelines[$id] = $pipeline;
    }
  }

  /**
   * {@inheritdoc}
   */
  public function delete(FlowDropPipelineInterface $pipeline): void {
    $id = $pipeline->id();
    if ($id !== NULL) {
      unset($this->pipelines[$id]);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function resetCache(?array $ids = NULL): void {
    // For in-memory storage, cache reset is a no-op since there's
    // no static cache.
    // The data is already "fresh" as it's stored directly in the object.
  }

  /**
   * Clears all stored pipelines.
   *
   * Useful for testing or resetting state between workflow executions.
   */
  public function clear(): void {
    $this->pipelines = [];
  }

  /**
   * Gets all stored pipelines.
   *
   * @return \Drupal\flowdrop_pipeline\Entity\FlowDropPipelineInterface[]
   *   All stored pipelines.
   */
  public function getAll(): array {
    return $this->pipelines;
  }

}
