<?php
/**
 * Storage Settings Validator
 *
 * @package Ugcify\Storage
 */

namespace Ugcify\Storage;

use WP_Error;

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

/**
 * Class StorageValidator
 *
 * Validates admin input for storage settings before they are saved.
 * PHP 7.4 compatible.
 *
 * SOLID — Single Responsibility: validation rules only, no persistence or HTTP concerns.
 */
class StorageValidator {

	/**
	 * Required fields and their human-readable labels.
	 *
	 * @var array
	 */
	private static $required_fields = array(
		'bucket'            => 'Bucket Name',
		'region'            => 'Region',
		'access_key_id'     => 'Access Key ID',
		'secret_access_key' => 'Secret Access Key',
	);

	/**
	 * Validate storage settings input.
	 *
	 * Only validates required fields when S3 is being enabled.
	 * If just saving disabled state, only the 'enabled' field is needed.
	 *
	 * @param array $input Raw input from the REST request.
	 * @return true|WP_Error True on valid. WP_Error with all failures on invalid.
	 */
	public static function validate( array $input ) {
		$errors = array();

		// If enabling S3, all credential fields are required.
		$is_enabling = ! empty( $input['enabled'] );

		if ( $is_enabling ) {
			// Check required fields — key fields are only required when no saved key exists.
			$saved_settings = get_option( 'ugcify_storage_settings', array() );

			foreach ( self::$required_fields as $field => $label ) {
				$value = isset( $input[ $field ] ) ? trim( (string) $input[ $field ] ) : '';

				// For key fields: skip required check if a key is already saved.
				$is_key_field  = in_array( $field, array( 'access_key_id', 'secret_access_key' ), true );
				$saved_key     = 'access_key_id' === $field ? 'access_key_encrypted' : 'secret_key_encrypted';
				$already_saved = $is_key_field && ! empty( $saved_settings[ $saved_key ] );

				if ( ! $already_saved && '' === $value ) {
					/* translators: %s: field label */
					$errors[] = sprintf( __( '%s is required.', 'ugcify' ), $label );
				}
			}
		}

		// Bucket name: alphanumeric, hyphens, dots only (S3 rules).
		if ( ! empty( $input['bucket'] ) ) {
			$bucket = sanitize_text_field( $input['bucket'] );
			if ( ! preg_match( '/^[a-z0-9][a-z0-9\-\.]{1,61}[a-z0-9]$/', $bucket ) ) {
				$errors[] = __( 'Bucket Name must be 3–63 characters, lowercase alphanumeric, hyphens, or dots.', 'ugcify' );
			}
		}

		// Region: valid AWS region code format if provided.
		if ( isset( $input['region'] ) && '' !== trim( (string) $input['region'] ) ) {
			$region = sanitize_text_field( $input['region'] );
			if ( ! preg_match( '/^[a-z]{2}(-[a-z]+)+-[0-9]$/', $region ) ) {
				$errors[] = __( 'Region must be a valid AWS region code (e.g. us-east-1, eu-west-2).', 'ugcify' );
			}
		}

		// Custom endpoint: must be a valid URL if provided.
		if ( ! empty( $input['custom_endpoint'] ) ) {
			$url = esc_url_raw( $input['custom_endpoint'] );
			if ( ! filter_var( $url, FILTER_VALIDATE_URL ) ) {
				$errors[] = __( 'Custom Endpoint must be a valid URL (e.g. https://s3.custom-provider.com).', 'ugcify' );
			}
		}

		if ( ! empty( $errors ) ) {
			return new WP_Error(
				'validation_failed',
				implode( ' ', $errors ),
				array(
					'status' => 422,
					'errors' => $errors,
				)
			);
		}

		return true;
	}
}
