<?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\MemoryDelete;
use Drupal\flowdrop_memory\Service\MemoryManager;
use Drupal\Tests\UnitTestCase;
use Prophecy\PhpUnit\ProphecyTrait;

/**
 * Tests the MemoryDelete node processor.
 *
 * @coversDefaultClass \Drupal\flowdrop_memory\Plugin\FlowDropNodeProcessor\MemoryDelete
 * @group flowdrop_memory
 */
class MemoryDeleteTest 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\MemoryDelete
   */
  private MemoryDelete $processor;

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

    $this->memoryManager = $this->prophesize(MemoryManager::class);
    $this->processor = new MemoryDelete(
      [],
      'memory_delete',
      ['id' => 'memory_delete'],
      $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) {
    $params = $this->prophesize(ParameterBagInterface::class);
    $params->getString('scope', 'global')->willReturn($scope);
    $params->getString('key')->willReturn($key);
    $params->getString('backend', 'static')->willReturn('static');
    return $params;
  }

  // ---------------------------------------------------------------------------
  // validateParams
  // ---------------------------------------------------------------------------

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

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

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

  /**
   * @covers ::validateParams
   */
  public function testValidateParamsSucceedsWithKeyAndOptionalScope(): void {
    $result = $this->processor->validateParams(['key' => 'chat_history', 'scope' => 'session']);
    $this->assertTrue($result->isValid());
  }

  // ---------------------------------------------------------------------------
  // process — delete behaviour
  // ---------------------------------------------------------------------------

  /**
   * @covers ::process
   */
  public function testProcessCallsDeleteOnManager(): void {
    $params = $this->stubParams('global', 'chat_history');
    $this->memoryManager->delete('global', '', 'chat_history', 'static')->shouldBeCalled();

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

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

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

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

  /**
   * @covers ::process
   */
  public function testProcessDeletesWithContextualPipelineScope(): void {
    $this->processor->setExecutionContext($this->makeContext(pipelineId: 'pl-99'));

    $params = $this->stubParams('pipeline', 'key');
    $this->memoryManager->delete('pipeline', 'pl-99', 'key', 'static')->shouldBeCalled();

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

  /**
   * @covers ::process
   */
  public function testProcessDeletesWithSessionScopeFromContext(): void {
    $this->processor->setExecutionContext($this->makeContext(metadata: ['session_id' => 'sess-abc']));

    $params = $this->stubParams('session', 'chat_history');
    $this->memoryManager->delete('session', 'sess-abc', 'chat_history', 'static')->shouldBeCalled();

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

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

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

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

  // ---------------------------------------------------------------------------
  // process — output shape
  // ---------------------------------------------------------------------------

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

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

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

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

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

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

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

    $params = $this->stubParams('workflow', 'key');
    $this->memoryManager->delete('workflow', 'wf-99', 'key', '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', 'key');
    $this->memoryManager->delete('global', '', 'key', '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);
  }

}
