<?php

declare(strict_types=1);

namespace SiteFort\Includes;

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

use SiteFort\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 = [
		'sitefort_dashboard_stats',
		'sitefort_dashboard_stats_disabled',
		'sitefort_dashboard_stats_pending_validation',
		'sitefort_dashboard_stats_monitor',
		'sitefort_dashboard_stats_enforce',
		'sitefort_self_update_check',
		'sitefort_cloud_intel_blocklist',
		'sitefort_network_report_buffer',
		'sitefort_waf_log_ingested',
		'sitefort_db_signatures',
		'sitefort_last_scan_alert',
		'sitefort_ip_readiness',
		'sitefort_ip_probe_recommendation',
		'sitefort_ip_probe_token',
		'sitefort_ip_probe_dispatched',
		'sitefort_auto_activate_otp_notice',
		'sitefort_server_rules_hash',
		'sitefort_server_rules_last_error',
		'sitefort_api_backoff_until',
		'sitefort_cloud_fail_count',
	];

	/**
	 * Fixed-key runtime state options that should be removed on full reset.
	 *
	 * @var string[]
	 */
	private const RESET_OPTION_KEYS = [
		'sitefort_active_lockout_registry',
		'sitefort_ip_lockout_meta',
		'sitefort_admin_ip_whitelist',
		'sitefort_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( 'sitefort_state_dirty' );
		LockoutRegistry::clear_all_lockouts();

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