<?php

declare(strict_types=1);

namespace Drupal\flowdrop\DTO;

/**
 * Represents a single validation error.
 *
 * Used within ValidationResult to provide detailed information
 * about validation failures.
 */
final class ValidationError {

  /**
   * Constructs a ValidationError.
   *
   * @param string $parameter
   *   The parameter name that failed validation.
   * @param string $message
   *   Human-readable error message.
   * @param string|null $code
   *   Optional machine-readable error code.
   */
  public function __construct(
    private readonly string $parameter,
    private readonly string $message,
    private readonly ?string $code = NULL,
  ) {}

  /**
   * Get the parameter name.
   *
   * @return string
   *   The parameter that failed validation.
   */
  public function getParameter(): string {
    return $this->parameter;
  }

  /**
   * Get the error message.
   *
   * @return string
   *   Human-readable error message.
   */
  public function getMessage(): string {
    return $this->message;
  }

  /**
   * Get the error code.
   *
   * @return string|null
   *   Machine-readable error code, or NULL if not set.
   */
  public function getCode(): ?string {
    return $this->code;
  }

  /**
   * Convert to array representation.
   *
   * @return array{parameter: string, message: string, code: string|null}
   *   Array representation of the error.
   */
  public function toArray(): array {
    return [
      "parameter" => $this->parameter,
      "message" => $this->message,
      "code" => $this->code,
    ];
  }

  /**
   * Create from array representation.
   *
   * @param array{parameter: string, message: string, code?: string|null} $data
   *   The array data.
   *
   * @return self
   *   A new ValidationError instance.
   */
  public static function fromArray(array $data): self {
    return new self(
      parameter: $data["parameter"],
      message: $data["message"],
      code: $data["code"] ?? NULL,
    );
  }

}
