<?php

namespace FleekDash\Core;

use FleekDash\Database\Core\MigrationManager;

defined('ABSPATH') || exit;

if (!function_exists('fleekdash_log_error')) {
    require_once FLEEKDASH_PLUGIN_DIR . 'includes/Core/debug-helpers.php';
}

/**
 * Runs pending database migrations without requiring WP-CLI.
 *
 * ActivationRunner marks the pipeline "completed" after first install; plugin updates
 * that only add new migration files would otherwise never execute. This class ensures
 * pending migrations apply on upgrade and on normal loads when still outstanding.
 */
final class AutoMigrationRunner
{
    /**
     * Execute all pending migrations. Safe to call multiple times; MigrationManager is idempotent.
     */
    public static function runPending(): void
    {
        if (defined('WP_INSTALLING') && WP_INSTALLING) {
            return;
        }

        try {
            $manager = new MigrationManager();
            if (empty($manager->pending())) {
                return;
            }

            self::logMigrationResults($manager->run());
        } catch (\Throwable $e) {
            fleekdash_log_error('[FleekDash] Auto-migration failed: ' . $e->getMessage());
        }
    }

    /**
     * @param array<string, mixed> $results
     */
    private static function logMigrationResults(array $results): void
    {
        $nothingToMigrate = isset($results['message']) && $results['message'] === 'Nothing to migrate';

        if ($nothingToMigrate) {
            return;
        }

        if (!empty($results['stopped'])) {
            $migrations = $results['migrations'] ?? [];
            $last = is_array($migrations) && $migrations !== [] ? end($migrations) : null;
            $err = is_array($last) ? ($last['error'] ?? 'unknown') : 'unknown';
            fleekdash_log_error('[FleekDash] Auto-migration stopped: ' . $err);
        } else {
            $count = isset($results['migrations']) ? count($results['migrations']) : 0;
            if ($count > 0) {
                fleekdash_log_info(sprintf('[FleekDash] Auto-migration: %d migration(s) applied.', $count));
            }
        }
    }
}
