<?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 delete node processor.
 *
 * Deletes a single key from memory using fully explicit scope and scope_id.
 * No auto-population from execution context.
 *
 * Use this processor when you need to:
 * - Delete a key written by a different workflow or pipeline
 * - Use a custom scoping strategy (e.g., keyed by user ID)
 * - Delete memory outside a standard FlowDrop execution context
 *
 * 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 deleting memory belonging to other users or executions.
 *
 * @see \Drupal\flowdrop_memory\Plugin\FlowDropNodeProcessor\MemoryDelete
 */
#[FlowDropNodeProcessor(
  id: 'memory_delete_raw',
  label: new TranslatableMarkup('Memory Delete (Explicit)'),
  description: 'Delete a key from memory with fully explicit scope and scope ID. No auto-population from execution context.',
  version: '1.0.0',
)]
class MemoryDeleteRaw 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', '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');
    $backend = $params->getString('backend', 'static');

    $this->memoryManager->delete($scope, $scopeId, $key, $backend);

    return [
      'success' => TRUE,
      '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 delete.',
        ],
        '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' => [
        'success' => [
          'type'        => 'boolean',
          'description' => 'Always TRUE when the delete completes (even if the key did not exist).',
        ],
        'key' => [
          'type'        => 'string',
          'description' => 'The key that was deleted.',
        ],
        'scope' => [
          'type'        => 'string',
          'description' => 'The scope used.',
        ],
      ],
    ];
  }

}
