<?php

declare(strict_types=1);

namespace SecurWP\Includes;

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

use SecurWP\Modules\Hardening\LockoutRegistry;

/**
 * Clears known plugin cache transients and reset-time runtime state.
 *
 * Cache-flush operations must not silently clear live security controls such
 * as bans or login lockouts. Full plugin reset can clear those states, but a
 * transient/cache flush should only remove cache-like entries.
 */
final class TransientCleanup {
	/**
	 * Known fixed-key cache/UI transients that are safe to purge on demand.
	 *
	 * @var string[]
	 */
	private const CACHE_TRANSIENT_KEYS = [
		'securwp_dashboard_stats',
		'securwp_dashboard_stats_disabled',
		'securwp_dashboard_stats_pending_validation',
		'securwp_dashboard_stats_monitor',
		'securwp_dashboard_stats_enforce',
		'securwp_self_update_check',
		'securwp_cloud_intel_blocklist',
		'securwp_network_report_buffer',
		'securwp_waf_log_ingested',
		'securwp_db_signatures',
		'securwp_last_scan_alert',
		'securwp_ip_readiness',
		'securwp_ip_probe_recommendation',
		'securwp_ip_probe_token',
		'securwp_ip_probe_dispatched',
		'securwp_auto_activate_otp_notice',
		'securwp_server_rules_hash',
		'securwp_server_rules_last_error',
		'securwp_api_backoff_until',
		'securwp_cloud_fail_count',
	];

	/**
	 * Fixed-key runtime state options that should be removed on full reset.
	 *
	 * @var string[]
	 */
	private const RESET_OPTION_KEYS = [
		'securwp_active_lockout_registry',
		'securwp_ip_lockout_meta',
		'securwp_admin_ip_whitelist',
		'securwp_firewall_effective_mode_state',
	];

	/**
	 * Clear cache-like plugin transients without touching live security state.
	 */
	public static function clear_known_cache_transients(): void {
		foreach ( self::CACHE_TRANSIENT_KEYS as $key ) {
			delete_transient( $key );
		}
	}

	/**
	 * Clear runtime state that a full plugin reset is expected to remove.
	 */
	public static function clear_reset_runtime_state(): void {
		self::clear_known_cache_transients();
		delete_transient( 'securwp_state_dirty' );
		LockoutRegistry::clear_all_lockouts();

		foreach ( self::RESET_OPTION_KEYS as $key ) {
			delete_option( $key );
		}
	}
}
