<?php
/**
 * Lightweight migration runner for WP Mail Doctor.
 *
 * @package MailDoctor
 */

namespace MailDoctor\Migrations;

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

/**
 * Executes incremental migrations for plugin data durability.
 */
class Migrations {
	public const DB_VERSION            = 1;
	protected const OPTION_DB_VERSION  = 'mail_doctor_db_version';
	protected const OPTION_MIGRATED_AT = 'mail_doctor_db_version_migrated_at';

	protected static bool $ran = false;

	/**
	 * Run pending migrations if required.
	 *
	 * @return void
	 */
	public static function run(): void {
		if ( self::$ran ) {
			return;
		}

		self::$ran = true;

		$current_version = (int) get_option( self::OPTION_DB_VERSION, 0 );
		if ( $current_version >= self::DB_VERSION ) {
			return;
		}

		$migrations = array(
			1 => 'migrate_0001_seed_history_entries',
		);

		foreach ( $migrations as $version => $method ) {
			if ( $version <= $current_version ) {
				continue;
			}

			if ( ! method_exists( __CLASS__, $method ) ) {
				continue;
			}

			try {
				self::{$method}();
			} catch ( \Throwable $exception ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundInImplementedInterface
				error_log( sprintf( 'Mail Doctor migration %1$s failed: %2$s', $method, $exception->getMessage() ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
				return;
			}
		}

		update_option( self::OPTION_DB_VERSION, self::DB_VERSION, false );
		update_option( self::OPTION_MIGRATED_AT, time(), false );
	}

	/**
	 * Previously seeded template history for existing CPT entries.
	 *
	 * No-op: The email template editor feature has been removed.
	 *
	 * @return void
	 */
	protected static function migrate_0001_seed_history_entries(): void {
		// No-op: email template feature removed.
	}
}
