<?php

declare(strict_types=1);

namespace Drupal\flowdrop_runtime\Event;

use Drupal\flowdrop_job\FlowDropJobInterface;
use Symfony\Contracts\EventDispatcher\Event;

/**
 * Event dispatched immediately after a pipeline job finishes executing.
 *
 * Fired for both completed and failed jobs so subscribers can react
 * to each node's result without waiting for the full orchestration run.
 * Dispatched by AbstractOrchestratorBase::executeJob() and by any orchestrator
 * that implements its own execution loop (e.g. StateGraphOrchestrator).
 *
 * @internal
 */
class JobCompletedEvent extends Event {

  /**
   * The event name.
   */
  public const string NAME = 'flowdrop_runtime.job.completed';

  /**
   * The job entity after execution.
   */
  private readonly FlowDropJobInterface $job;

  /**
   * Playground context extracted from the pipeline execution context, or NULL.
   */
  private readonly ?PlaygroundContext $playgroundContext;

  /**
   * The pipeline execution ID for this job.
   */
  private readonly string $executionId;

  /**
   * Constructs a new JobCompletedEvent.
   *
   * @param \Drupal\flowdrop_job\FlowDropJobInterface $job
   *   The job entity after execution (status already updated and saved).
   * @param array<string, mixed> $pipelineContext
   *   The pipeline execution context (from
   *   FlowDropPipelineRuntimeInterface::getExecutionContext()).
   * @param string $executionId
   *   The execution ID for this pipeline run.
   */
  public function __construct(FlowDropJobInterface $job, array $pipelineContext, string $executionId = '') {
    $this->job = $job;
    $this->executionId = $executionId;
    $this->playgroundContext = PlaygroundContext::fromPipelineContext($pipelineContext);
  }

  /**
   * Returns the job entity after execution.
   */
  public function getJob(): FlowDropJobInterface {
    return $this->job;
  }

  /**
   * Returns the playground context, or NULL when not running in a playground.
   */
  public function getPlaygroundContext(): ?PlaygroundContext {
    return $this->playgroundContext;
  }

  /**
   * Returns the execution ID for this pipeline run.
   */
  public function getExecutionId(): string {
    return $this->executionId;
  }

}
