<?php
/**
 * One-time migration from legacy flat SMTP settings.
 *
 * @package EmailSmtp
 * @since 1.1.0
 */

namespace EmailSmtp\Includes;

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

final class SettingsMigrator {

	/**
	 * Legacy v0 → v1 (provider architecture). Connections (v2) are handled by ConnectionStore.
	 *
	 * @param array<string, mixed> $settings
	 * @return array<string, mixed>
	 */
	public static function ensure_migrated( array $settings ): array {
		$version = (int) ( $settings['migration_version'] ?? 0 );
		if ( $version >= 1 ) {
			return $settings;
		}

		$host = trim( (string) ( $settings['smtp_host'] ?? '' ) );
		if ( empty( $settings['provider'] ) ) {
			$settings['provider'] = $host !== '' ? 'smtp' : 'wordpress';
		}

		if ( ! isset( $settings['force_from_email'] ) && isset( $settings['override_from'] ) ) {
			$settings['force_from_email'] = ! empty( $settings['override_from'] ) && (string) $settings['override_from'] !== '0' ? '1' : '0';
		}
		if ( ! isset( $settings['force_from_name'] ) && isset( $settings['override_from'] ) ) {
			$settings['force_from_name'] = ! empty( $settings['override_from'] ) && (string) $settings['override_from'] !== '0' ? '1' : '0';
		}

		if ( ! isset( $settings['smtp_autotls'] ) ) {
			$encryption = (string) ( $settings['smtp_encryption'] ?? 'tls' );
			$port       = (int) ( $settings['smtp_port'] ?? 587 );
			$settings['smtp_autotls'] = ( $encryption === 'tls' || ( $encryption === '' && $port === 587 ) ) ? '1' : '0';
		}

		if ( ! isset( $settings['smtp_timeout'] ) ) {
			$settings['smtp_timeout'] = '30';
		}

		$settings['migration_version'] = 1;
		$settings['_migration_dirty']  = true;

		return $settings;
	}

	/**
	 * Persist migration if needed.
	 *
	 * @param array<string, mixed> $settings
	 * @param callable             $saver fn(array $settings): void
	 * @return array<string, mixed>
	 */
	public static function maybe_persist( array $settings, callable $saver ): array {
		if ( empty( $settings['_migration_dirty'] ) ) {
			return $settings;
		}
		unset( $settings['_migration_dirty'] );
		$saver( $settings );
		return $settings;
	}
}
