<?php

/**
 * LolaCore � Migrator
 *
 * @package LolaCore
 * @license GPL-2.0-or-later
 */

declare(strict_types=1);

namespace LolaCore\Database;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Migrator
{
    /**
     * Checks if the database schema needs to be upgraded and runs migrations if necessary.
     *
     * Runs when either:
     *  - lolacore_db_version is behind LOLACORE_DB_VERSION (normal plugin update), or
     *  - any expected table is missing (self-heal after a partial/failed migration).
     *
     * The version option is only advanced when every table exists, so a failed
     * dbDelta does not strand sites in a "migrated" state without the new tables.
     */
    public static function maybeUpgrade(): void
    {
        require_once __DIR__ . '/Schema.php';

        $currentVersion   = get_option('lolacore_db_version', '0.0.0');
        $needsVersionBump = version_compare($currentVersion, LOLACORE_DB_VERSION, '<');
        $missingTables    = Schema::getMissingTables();

        if (!$needsVersionBump && $missingTables === []) {
            return;
        }

        Schema::create();

        $stillMissing = Schema::getMissingTables();
        if ($stillMissing !== []) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Migration integrity; dev-only signal (WP_DEBUG only).
                error_log('[LolaCore] DB migration incomplete. Missing tables: ' . implode(', ', $stillMissing));
            }
            return;
        }

        update_option('lolacore_db_version', LOLACORE_DB_VERSION);
    }
}
