<?php
/**
 * Validation exception class.
 *
 * @package PDFDraft
 */

namespace PDFDraft\Exceptions;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Exception thrown when validation fails.
 */
class ValidationException extends ServiceException {
	/**
	 * Validation errors by field.
	 *
	 * @var array<string, string[]>
	 */
	private array $errors = array();

	/**
	 * Constructor.
	 *
	 * @param string          $message  Exception message.
	 * @param array           $errors   Validation errors keyed by field name.
	 * @param int             $code     HTTP status code.
	 * @param \Throwable|null $previous Previous exception.
	 */
	public function __construct( string $message = 'Validation failed', array $errors = array(), int $code = 400, ?\Throwable $previous = null ) {
		parent::__construct( $message, $code, $previous );
		$this->errors = $errors;
	}

	/**
	 * Get validation errors.
	 *
	 * @return array<string, string[]>
	 */
	public function getErrors(): array {
		return $this->errors;
	}

	/**
	 * Add a validation error for a field.
	 *
	 * @param string $field   Field name.
	 * @param string $message Error message.
	 * @return void
	 */
	public function addError( string $field, string $message ): void {
		if ( ! isset( $this->errors[ $field ] ) ) {
			$this->errors[ $field ] = array();
		}
		$this->errors[ $field ][] = $message;
	}
}
