<?php

declare(strict_types=1);

namespace Drupal\Tests\flowdrop_memory\Unit\Plugin\FlowDropNodeProcessor;

use Drupal\flowdrop\DTO\ExecutionContextDTO;
use Drupal\flowdrop\DTO\ParameterBagInterface;
use Drupal\flowdrop_memory\Plugin\FlowDropNodeProcessor\MemoryWrite;
use Drupal\flowdrop_memory\Service\MemoryManager;
use Drupal\Tests\UnitTestCase;
use Prophecy\PhpUnit\ProphecyTrait;

/**
 * Tests the MemoryWrite node processor.
 *
 * @coversDefaultClass \Drupal\flowdrop_memory\Plugin\FlowDropNodeProcessor\MemoryWrite
 * @group flowdrop_memory
 */
class MemoryWriteTest extends UnitTestCase {

  use ProphecyTrait;

  /**
   * The memory manager mock.
   *
   * @var \Prophecy\Prophecy\ObjectProphecy|\Drupal\flowdrop_memory\Service\MemoryManager
   */
  private $memoryManager;

  /**
   * The processor under test.
   *
   * @var \Drupal\flowdrop_memory\Plugin\FlowDropNodeProcessor\MemoryWrite
   */
  private MemoryWrite $processor;

  /**
   * {@inheritdoc}
   */
  protected function setUp(): void {
    parent::setUp();

    $this->memoryManager = $this->prophesize(MemoryManager::class);
    $this->processor = new MemoryWrite(
      [],
      'memory_write',
      ['id' => 'memory_write'],
      $this->memoryManager->reveal(),
    );
  }

  /**
   * Builds an ExecutionContextDTO for testing.
   */
  private function makeContext(
    string $workflowId = 'wf-id',
    string $pipelineId = 'pl-id',
    string $executionId = 'ex-id',
    array $metadata = [],
  ): ExecutionContextDTO {
    return new ExecutionContextDTO([], $workflowId, $pipelineId, $executionId, 'node-id', $metadata);
  }

  /**
   * Stubs a ParameterBagInterface prophecy.
   */
  private function stubParams(string $scope, string $key, mixed $value, int $ttl = 0) {
    $params = $this->prophesize(ParameterBagInterface::class);
    $params->getString('scope', 'global')->willReturn($scope);
    $params->getString('key')->willReturn($key);
    $params->get('value')->willReturn($value);
    $params->getInt('ttl', 0)->willReturn($ttl);
    $params->getString('backend', 'static')->willReturn('static');
    return $params;
  }

  /**
   * @covers ::validateParams
   */
  public function testValidateParamsFailsWhenKeyMissing(): void {
    $result = $this->processor->validateParams(['value' => 'something']);
    $this->assertFalse($result->isValid());
  }

  /**
   * @covers ::validateParams
   */
  public function testValidateParamsFailsWhenKeyIsEmpty(): void {
    $result = $this->processor->validateParams(['key' => '', 'value' => 'something']);
    $this->assertFalse($result->isValid());
  }

  /**
   * @covers ::validateParams
   */
  public function testValidateParamsFailsWhenValueKeyAbsent(): void {
    $result = $this->processor->validateParams(['key' => 'my_key']);
    $this->assertFalse($result->isValid());
  }

  /**
   * @covers ::validateParams
   */
  public function testValidateParamsSucceedsWithNullValue(): void {
    // NULL is a valid value — the key must exist in the array.
    $result = $this->processor->validateParams(['key' => 'my_key', 'value' => NULL]);
    $this->assertTrue($result->isValid());
  }

  /**
   * @covers ::validateParams
   */
  public function testValidateParamsSucceedsWithStringValue(): void {
    $result = $this->processor->validateParams(['key' => 'my_key', 'value' => 'hello']);
    $this->assertTrue($result->isValid());
  }

  /**
   * @covers ::validateParams
   */
  public function testValidateParamsSucceedsWithArrayValue(): void {
    $result = $this->processor->validateParams(['key' => 'my_key', 'value' => [1, 2, 3]]);
    $this->assertTrue($result->isValid());
  }

  /**
   * @covers ::process
   */
  public function testProcessWritesToGlobalScope(): void {
    $params = $this->stubParams('global', 'counter', 99);
    $this->memoryManager->set('global', '', 'counter', 99, NULL, 'static')->shouldBeCalled();

    $this->processor->process($params->reveal());
  }

  /**
   * @covers ::process
   */
  public function testProcessWritesWithContextualWorkflowScope(): void {
    $this->processor->setExecutionContext($this->makeContext(workflowId: 'wf-42'));

    $params = $this->stubParams('workflow', 'my_key', 'my_value');
    $this->memoryManager->set('workflow', 'wf-42', 'my_key', 'my_value', NULL, 'static')->shouldBeCalled();

    $this->processor->process($params->reveal());
  }

  /**
   * @covers ::process
   */
  public function testProcessPassesTtlToBackendWhenPositive(): void {
    $params = $this->stubParams('global', 'key', 'val', 300);
    $this->memoryManager->set('global', '', 'key', 'val', 300, 'static')->shouldBeCalled();

    $this->processor->process($params->reveal());
  }

  /**
   * @covers ::process
   */
  public function testProcessPassesNullTtlToBackendWhenZero(): void {
    $params = $this->stubParams('global', 'key', 'val', 0);
    $this->memoryManager->set('global', '', 'key', 'val', NULL, 'static')->shouldBeCalled();

    $this->processor->process($params->reveal());
  }

  /**
   * @covers ::process
   */
  public function testProcessReturnsTrueForSuccess(): void {
    $params = $this->stubParams('global', 'key', 'value');
    $this->memoryManager->set('global', '', 'key', 'value', NULL, 'static')->shouldBeCalled();

    $output = $this->processor->process($params->reveal());

    $this->assertTrue($output['success']);
  }

  /**
   * @covers ::process
   */
  public function testProcessReturnsKeyInOutput(): void {
    $params = $this->stubParams('global', 'my_key', 'val');
    $this->memoryManager->set('global', '', 'my_key', 'val', NULL, 'static')->shouldBeCalled();

    $output = $this->processor->process($params->reveal());

    $this->assertSame('my_key', $output['key']);
  }

  /**
   * @covers ::process
   */
  public function testProcessReturnsScopeInOutput(): void {
    $params = $this->stubParams('global', 'key', 'val');
    $this->memoryManager->set('global', '', 'key', 'val', NULL, 'static')->shouldBeCalled();

    $output = $this->processor->process($params->reveal());

    $this->assertSame('global', $output['scope']);
  }

  /**
   * @covers ::process
   */
  public function testProcessReturnsResolvedScopeIdInOutput(): void {
    $this->processor->setExecutionContext($this->makeContext(workflowId: 'wf-99'));

    $params = $this->stubParams('workflow', 'key', 'val');
    $this->memoryManager->set('workflow', 'wf-99', 'key', 'val', NULL, 'static')->shouldBeCalled();

    $output = $this->processor->process($params->reveal());

    $this->assertSame('wf-99', $output['resolved_scope_id']);
  }

  /**
   * @covers ::process
   */
  public function testProcessExposesAllRequiredOutputKeys(): void {
    $params = $this->stubParams('global', 'k', 'v');
    $this->memoryManager->set('global', '', 'k', 'v', NULL, 'static')->shouldBeCalled();

    $output = $this->processor->process($params->reveal());

    $this->assertArrayHasKey('success', $output);
    $this->assertArrayHasKey('key', $output);
    $this->assertArrayHasKey('scope', $output);
    $this->assertArrayHasKey('resolved_scope_id', $output);
  }

}
