<?php

declare(strict_types=1);

namespace Drupal\flowdrop_runtime\Service\Storage;

use Drupal\Component\Uuid\UuidInterface;
use Drupal\flowdrop_pipeline\Entity\FlowDropPipelineRuntimeInterface;

/**
 * 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\FlowDropPipelineRuntimeInterface[]
   */
  protected array $pipelines = [];

  /**
   * Constructs a new InMemoryPipelineStorage.
   *
   * @param \Drupal\Component\Uuid\UuidInterface $uuid
   *   The UUID generator service.
   */
  public function __construct(
    private readonly UuidInterface $uuid,
  ) {}

  /**
   * {@inheritdoc}
   */
  public function create(array $data): InMemoryPipeline {
    $uuidValue = $this->uuid->generate();
    $data['id'] = 'inmem_' . $uuidValue;
    $data['uuid'] = $uuidValue;
    return new InMemoryPipeline($data, $this->uuid);
  }

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

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

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

  /**
   * {@inheritdoc}
   */
  public function resetCache(?array $ids = NULL): void {
    // No-op: in-memory storage has no static cache.
  }

  /**
   * Clears all stored pipelines.
   */
  public function clear(): void {
    $this->pipelines = [];
  }

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

}
