<?php

declare( strict_types=1 );

namespace StrykeWP\Core;

/**
 * Handles plugin activation and deactivation lifecycle.
 *
 * Static methods are used because WordPress activation hooks fire before
 * `plugins_loaded`, so no service container is available at that point.
 *
 * @package StrykeWP\Core
 */
final class Installer {

	/**
	 * Runs when the plugin is activated.
	 *
	 * - Stores the installed version for future upgrade detection.
	 * - Sets default module states (all disabled by default on fresh install).
	 * - Creates all custom DB tables via SchemaManager (idempotent).
	 * - Flushes rewrite rules so any custom endpoints register cleanly.
	 */
	public static function activate(): void {
		// Record installed version (used by upgrade routines).
		if ( ! get_option( OptionManager::PREFIX . 'version' ) ) {
			add_option( OptionManager::PREFIX . 'version', STRYKE_WP_VERSION );
			add_option( OptionManager::PREFIX . 'installed_at', current_time( 'mysql' ) );

			// Default module states on fresh install: all enabled.
			$default_modules = [ 'connector', 'branding', 'backup', 'wip_mode' ];
			foreach ( $default_modules as $module_id ) {
				add_option( OptionManager::PREFIX . "module_{$module_id}_enabled", true );
			}
		}

		// Create all custom DB tables now so they exist even before modules
		// are individually enabled. dbDelta is idempotent — safe to re-run.
		SchemaManager::create_all();

		// Flush rewrite rules cleanly (deferred via option flag).
		update_option( OptionManager::PREFIX . 'flush_rewrite_rules', true );

		// Set activation notice transient for the welcome message.
		PluginMeta::set_activation_notice();
	}

	/**
	 * Runs when the plugin is deactivated.
	 *
	 * - Clears all scheduled cron events owned by this plugin.
	 * - Flushes rewrite rules to remove any custom endpoints.
	 *
	 * NOTE: Data (options, tables) is intentionally preserved on deactivation.
	 * Full cleanup only happens via uninstall.php.
	 */
	public static function deactivate(): void {
		// Delegate cron cleanup to CronManager (single source of truth).
		CronManager::clear_all();

		// Flush rewrite rules on next page load.
		flush_rewrite_rules();
	}
}
