<?php

declare(strict_types=1);

namespace SecurWP\Modules\Settings;

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

/**
 * Defines the schema for global plugin settings owned by the Settings module.
 *
 * Other modules register their own schemas via SettingsProvider.
 * This class only covers settings persisted in the global settings column of
 * the SecurWP settings store.
 */
class SettingsSchema {

	/**
	 * Schema for settings directly owned by the Settings module.
	 *
	 * @return array<string, array{type: string, default: mixed}>
	 */
	public static function get_owned_schema(): array {
		return [
			'notification_email'   => [
				'type'    => 'email',
				'default' => get_option( 'admin_email' ),
			],
			'data_retention_days'  => [
				'type'    => 'integer',
				'default' => 90,
				'minimum' => 1,
				'maximum' => 3650,
			],
			'audit_log_enabled' => [
				'type'    => 'boolean',
				'default' => true,
			],
			'audit_log_storage'    => [
				'type'    => 'string',
				'default' => 'database',
			],
			'audit_file_retention_days' => [
				'type'    => 'integer',
				'default' => 90,
				'minimum' => 1,
				'maximum' => 3650,
			],
			'audit_log_level' => [
				'type'    => 'string',
				'default' => 'standard',
			],
			// System Config
			'server_type' => [
				'type'    => 'string',
				'default' => 'auto',
			],
			'nginx_file' => [
				'type'    => 'string',
				'default' => '',
			],
			'write_to_files' => [
				'type'    => 'boolean',
				'default' => true,
			],
		];
	}

	/**
	 * Sanitize a value against its schema definition.
	 *
	 * @param mixed  $value Raw input value.
	 * @param array  $schema Schema entry with 'type' and optional constraints.
	 * @return mixed Sanitized value.
	 */
	public static function sanitize( $value, array $schema ) {
		switch ( $schema['type'] ) {
			case 'boolean':
				return filter_var( $value, FILTER_VALIDATE_BOOLEAN );

			case 'integer':
				$int = absint( $value );
				if ( isset( $schema['minimum'] ) && $int < $schema['minimum'] ) {
					$int = $schema['minimum'];
				}
				if ( isset( $schema['maximum'] ) && $int > $schema['maximum'] ) {
					$int = $schema['maximum'];
				}
				return $int;

			case 'email':
				$email = sanitize_email( (string) $value );
				return is_email( $email ) ? $email : ( $schema['default'] ?? '' );

			case 'string':
			default:
				return sanitize_text_field( (string) $value );
		}
	}
}
