<?php
/**
 * Request validation helper.
 *
 * @package PDFDraft
 */

namespace PDFDraft\Support\Validation;

use PDFDraft\Exceptions\ValidationException;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Static helper for validating request data.
 */
class RequestValidator {

	/**
	 * Validate that required fields are present.
	 *
	 * @param array<string, mixed> $data     Data to validate.
	 * @param array<string>        $required Required field names.
	 * @throws ValidationException If validation fails.
	 * @return void
	 */
	public static function requireFields( array $data, array $required ): void {
		$errors = array();

		foreach ( $required as $field ) {
			if ( ! isset( $data[ $field ] ) || ( is_string( $data[ $field ] ) && '' === trim( $data[ $field ] ) ) ) {
				$errors[ $field ] = array( sprintf( 'Field "%s" is required.', $field ) );
			}
		}

		if ( ! empty( $errors ) ) {
			throw new ValidationException( 'Validation failed', $errors ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
		}
	}

	/**
	 * Validate data URL format.
	 *
	 * @param string $dataUrl   Data URL to validate.
	 * @param string $fieldName Field name for error messages.
	 * @throws ValidationException If validation fails.
	 * @return void
	 */
	public static function validateDataUrl( string $dataUrl, string $fieldName = 'dataUrl' ): void {
		// phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- exception messages are not rendered as HTML output.
		if ( empty( $dataUrl ) ) {
			throw new ValidationException(
				'Validation failed',
				array( $fieldName => array( 'Data URL cannot be empty.' ) )
			);
		}

		if ( ! preg_match( '/^data:image\/([a-z]+);base64,/', $dataUrl ) ) {
			throw new ValidationException(
				'Validation failed',
				array( $fieldName => array( 'Invalid data URL format. Expected format: data:image/{type};base64,{data}' ) )
			);
		}
		// phpcs:enable WordPress.Security.EscapeOutput.ExceptionNotEscaped
	}

	/**
	 * Validate that a value is not empty.
	 *
	 * @param mixed  $value     Value to validate.
	 * @param string $fieldName Field name for error messages.
	 * @throws ValidationException If validation fails.
	 * @return void
	 */
	public static function validateNotEmpty( $value, string $fieldName ): void {
		if ( empty( $value ) || ( is_string( $value ) && '' === trim( $value ) ) ) {
			// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- exception messages are not rendered as HTML output.
			throw new ValidationException( 'Validation failed', array( $fieldName => array( sprintf( 'Field "%s" cannot be empty.', $fieldName ) ) ) );
		}
	}
}
