<?php

declare(strict_types=1);

namespace Drupal\flowdrop_memory\Plugin\FlowDropNodeProcessor;

use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\flowdrop\Attribute\FlowDropNodeProcessor;
use Drupal\flowdrop\DTO\ParameterBagInterface;
use Drupal\flowdrop\DTO\ValidationError;
use Drupal\flowdrop\DTO\ValidationResult;
use Drupal\flowdrop\Plugin\FlowDropNodeProcessor\AbstractFlowDropNodeProcessor;
use Drupal\flowdrop_memory\Service\MemoryManager;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Explicit memory read node processor.
 *
 * Reads a value from memory using fully explicit scope and scope_id parameters.
 * No auto-population from execution context — scope_id is always what you wire
 * in.
 *
 * Use this processor when you need to:
 * - Read memory written by a different workflow or pipeline
 * - Use a custom scoping strategy (e.g., keyed by user ID, node ID)
 * - Access memory outside the standard execution context scopes
 *
 * SECURITY NOTE: This processor accepts an arbitrary scope_id with no
 * ownership validation. It is an administrator/developer-tier tool and must
 * only be used in workflows whose execution is restricted to trusted roles.
 * Do not expose it in workflows accessible to untrusted users, as it could
 * allow reading memory belonging to other users or executions.
 *
 * @see \Drupal\flowdrop_memory\Plugin\FlowDropNodeProcessor\MemoryRead
 */
#[FlowDropNodeProcessor(
  id: 'memory_read_raw',
  label: new TranslatableMarkup('Memory Read (Explicit)'),
  description: 'Read a value from memory with fully explicit scope and scope ID. No auto-population from execution context.',
  version: '1.0.0',
)]
class MemoryReadRaw extends AbstractFlowDropNodeProcessor {

  /**
   * {@inheritdoc}
   */
  public function __construct(
    array $configuration,
    string $plugin_id,
    mixed $plugin_definition,
    private readonly MemoryManager $memoryManager,
  ) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition): static {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('flowdrop_memory.manager'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function validateParams(array $params): ValidationResult {
    $errors = [];
    if (empty($params['scope'])) {
      $errors[] = new ValidationError('scope', 'Memory scope is required.');
    }
    if (empty($params['key'])) {
      $errors[] = new ValidationError('key', 'Memory key is required.');
    }
    return empty($errors) ? ValidationResult::success() : ValidationResult::failure($errors);
  }

  /**
   * {@inheritdoc}
   */
  public function process(ParameterBagInterface $params): array {
    $scope = $params->getString('scope');
    $scopeId = $params->getString('scope_id', '');
    $key = $params->getString('key');
    $default = $params->get('default_value');
    $backend = $params->getString('backend', 'static');

    $value = $this->memoryManager->get($scope, $scopeId, $key, $default, $backend);
    $found = $this->memoryManager->has($scope, $scopeId, $key, $backend);

    return [
      'value' => $value,
      'found' => $found,
      'key'   => $key,
      'scope' => $scope,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getParameterSchema(): array {
    return [
      'type' => 'object',
      'properties' => [
        'scope' => [
          'type'        => 'string',
          'title'       => 'Scope',
          'description' => 'The memory scope (any string).',
        ],
        'scope_id' => [
          'type'        => 'string',
          'title'       => 'Scope ID',
          'description' => 'The scope identifier. Leave blank if not applicable.',
          'default'     => '',
        ],
        'key' => [
          'type'        => 'string',
          'title'       => 'Key',
          'description' => 'The memory key to read.',
        ],
        'default_value' => [
          'type'        => 'mixed',
          'title'       => 'Default Value',
          'description' => 'Value to return if the key does not exist.',
          'default'     => NULL,
        ],
        'backend' => [
          'type'        => 'string',
          'title'       => 'Memory Backend',
          'description' => 'The storage backend to use.',
          'enum'        => ['static', 'cached', 'entity'],
          'default'     => 'static',
        ],
      ],
      'required' => ['scope', 'key', 'backend'],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getOutputSchema(): array {
    return [
      'type' => 'object',
      'properties' => [
        'value' => [
          'type'        => 'mixed',
          'description' => 'The retrieved value, or the default value if not found.',
        ],
        'found' => [
          'type'        => 'boolean',
          'description' => 'Whether the key existed in memory.',
        ],
        'key' => [
          'type'        => 'string',
          'description' => 'The key that was read.',
        ],
        'scope' => [
          'type'        => 'string',
          'description' => 'The scope used for the read.',
        ],
      ],
    ];
  }

}
