<?php

declare(strict_types=1);

namespace Drupal\flowdrop_stategraph\Exception;

use Drupal\flowdrop\Exception\FlowDropException;

/**
 * Exception thrown when maximum iterations are exceeded.
 *
 * This exception is thrown as a safety measure to prevent infinite loops
 * in workflows with conditional edge routing that loops back.
 *
 * @api
 */
class MaxIterationsException extends FlowDropException {

  /**
   * Constructs a new MaxIterationsException.
   *
   * @param int $maxIterations
   *   The maximum iterations limit that was exceeded.
   * @param int $currentIterations
   *   The current iteration count.
   * @param string $nodeId
   *   The node ID where the limit was reached.
   * @param \Throwable|null $previous
   *   Previous exception for chaining.
   */
  public function __construct(
    public readonly int $maxIterations,
    public readonly int $currentIterations,
    public readonly string $nodeId = "",
    ?\Throwable $previous = NULL,
  ) {
    $message = sprintf(
      "Maximum iterations (%d) exceeded at iteration %d",
      $maxIterations,
      $currentIterations
    );

    if ($nodeId !== "") {
      $message .= sprintf(" while executing node '%s'", $nodeId);
    }

    $message .= ". This may indicate an infinite loop in the workflow. " .
      "Consider adding termination conditions or increasing max_iterations in settings.";

    parent::__construct($message, 0, $previous);
  }

}
