<?php

namespace FleekDash\Core;

defined('ABSPATH') || exit;

/**
 * Handles plugin upgrade process completion (migrations, language migration, etc.).
 */
class PluginUpgraderHandler
{
    public static function onProcessComplete($upgrader, array $options): void // NOSONAR S1172 - $upgrader required by WordPress hook
    {
        if (!self::isFleekDashUpdate($options)) {
            return;
        }

        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('FleekDash Update: Running pending DB migrations and scheduling activation tasks.');
        }

        // Activation pipeline is skipped when already "completed"; new migration files must run here.
        AutoMigrationRunner::runPending();

        ActivationRunner::scheduleAsyncActivation();
        self::runLanguageMigration();
    }

    private static function isFleekDashUpdate(array $options): bool
    {
        $is_plugin_update = ($options['type'] ?? '') === 'plugin' && ($options['action'] ?? '') === 'update';
        $has_plugins = isset($options['plugins']) && is_array($options['plugins']);
        $plugin_file = plugin_basename(FLEEKDASH_PLUGIN_FILE);
        $includes_fleekdash = $has_plugins && in_array($plugin_file, $options['plugins'], true);

        return $is_plugin_update && $includes_fleekdash;
    }

    private static function runLanguageMigration(): void
    {
        if (!class_exists('\FleekDash\Core\LanguageMigration')) {
            return;
        }

        $lang_results = \FleekDash\Core\LanguageMigration::migrate_v2_2_0();

        if (defined('WP_DEBUG') && WP_DEBUG) {
            $migrated = count($lang_results['migrated']);
            if ($migrated > 0) {
                error_log("FleekDash Update: Migrated {$migrated} language(s) to safe location");
            }
        }
    }
}
