<?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\Plugin\FlowDropNodeProcessor\ExecutionContextAwareInterface;
use Drupal\flowdrop_memory\Service\MemoryManager;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Context-aware memory write node processor.
 *
 * Writes a value to the configured memory backend. The scope ID is
 * automatically derived from the current execution context.
 * See MemoryRead for the full scope resolution rules.
 *
 * TTL sets the time-to-live in seconds. A value of 0 (the default) means the
 * record never expires. TTL is silently ignored by backends that do not
 * support it (e.g., the static backend).
 *
 * @see \Drupal\flowdrop_memory\Plugin\FlowDropNodeProcessor\MemoryRead
 * @see \Drupal\flowdrop_memory\Plugin\FlowDropNodeProcessor\MemoryWriteRaw
 */
#[FlowDropNodeProcessor(
  id: 'memory_write',
  label: new TranslatableMarkup('Memory Write'),
  description: 'Write a value to scoped memory. Scope ID is automatically derived from the execution context.',
  version: '1.0.0',
)]
class MemoryWrite extends AbstractFlowDropNodeProcessor implements ExecutionContextAwareInterface {

  use ScopeResolutionTrait;

  /**
   * {@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['key'])) {
      $errors[] = new ValidationError('key', 'Memory key is required.');
    }
    if (!array_key_exists('value', $params)) {
      $errors[] = new ValidationError('value', 'Memory value is required.');
    }
    return empty($errors) ? ValidationResult::success() : ValidationResult::failure($errors);
  }

  /**
   * {@inheritdoc}
   */
  public function process(ParameterBagInterface $params): array {
    $scope = $params->getString('scope', 'global');
    $key = $params->getString('key');
    $value = $params->get('value');
    $ttl = $params->getInt('ttl', 0);
    $backend = $params->getString('backend', 'static');

    $resolvedScopeId = $this->resolveScopeId($scope);
    $this->memoryManager->set($scope, $resolvedScopeId, $key, $value, $ttl > 0 ? $ttl : NULL, $backend);

    return [
      'success'           => TRUE,
      'key'               => $key,
      'scope'             => $scope,
      'resolved_scope_id' => $resolvedScopeId,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getParameterSchema(): array {
    return [
      'type' => 'object',
      'properties' => [
        'scope' => [
          'type'        => 'string',
          'title'       => 'Scope',
          'description' => 'The memory scope. Common values: global, workflow, pipeline, execution, session.',
          'enum'        => ['global', 'workflow', 'pipeline', 'execution', 'session'],
          'default'     => 'global',
        ],
        'key' => [
          'type'        => 'string',
          'title'       => 'Key',
          'description' => 'The memory key to write.',
        ],
        'value' => [
          'type'        => 'mixed',
          'title'       => 'Value',
          'description' => 'The value to store.',
        ],
        'ttl' => [
          'type'        => 'integer',
          'title'       => 'TTL (seconds)',
          'description' => 'Time-to-live in seconds. 0 means no expiry. Ignored by backends that do not support TTL.',
          'default'     => 0,
          'minimum'     => 0,
        ],
        'backend' => [
          'type'        => 'string',
          'title'       => 'Memory Backend',
          'description' => 'The storage backend to use.',
          'enum'        => ['static', 'cached', 'entity'],
          'default'     => 'static',
        ],
      ],
      'required' => ['key', 'value', 'backend'],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getOutputSchema(): array {
    return [
      'type' => 'object',
      'properties' => [
        'success' => [
          'type'        => 'boolean',
          'description' => 'Always TRUE when the write succeeds.',
        ],
        'key' => [
          'type'        => 'string',
          'description' => 'The key that was written.',
        ],
        'scope' => [
          'type'        => 'string',
          'description' => 'The scope used for the write.',
        ],
        'resolved_scope_id' => [
          'type'        => 'string',
          'description' => 'The scope ID that was actually used (after auto-resolution).',
        ],
      ],
    ];
  }

}
