<?php

declare(strict_types=1);

namespace Drupal\flowdrop\DTO\Tool;

/**
 * Immutable {@see ToolResultInterface} value object.
 *
 * Construct via the {@see self::success()} and {@see self::error()} factories
 * rather than the constructor directly.
 *
 * @api
 */
final class ToolResult implements ToolResultInterface {

  /**
   * Constructs a ToolResult.
   *
   * @param bool $success
   *   Whether the tool ran successfully.
   * @param array<string, mixed> $data
   *   The tool's output data.
   * @param string|null $error
   *   The error message, when not successful.
   */
  private function __construct(
    private readonly bool $success,
    private readonly array $data,
    private readonly ?string $error,
  ) {}

  /**
   * Creates a successful result.
   *
   * @param array<string, mixed> $data
   *   The tool's output data.
   *
   * @return self
   *   The result.
   */
  public static function success(array $data): self {
    return new self(TRUE, $data, NULL);
  }

  /**
   * Creates a failed result.
   *
   * @param string $message
   *   The error message.
   *
   * @return self
   *   The result.
   */
  public static function error(string $message): self {
    return new self(FALSE, [], $message);
  }

  /**
   * {@inheritdoc}
   */
  public function isSuccess(): bool {
    return $this->success;
  }

  /**
   * {@inheritdoc}
   */
  public function getData(): array {
    return $this->data;
  }

  /**
   * {@inheritdoc}
   */
  public function getError(): ?string {
    return $this->error;
  }

  /**
   * {@inheritdoc}
   */
  public function toArray(): array {
    return [
      "success" => $this->success,
      "data" => $this->data,
      "error" => $this->error,
    ];
  }

}
