<?php
namespace FleekDash\Database\Core;

defined('ABSPATH') || exit;

/**
 * Migration Installer
 *
 * Creates and manages the migrations tracking table
 */
class MigrationInstaller
{
    /**
     * Install migrations tracking table
     */
    public static function install(): void
    {
        global $wpdb;
        $table = $wpdb->prefix . 'fleekdash_migrations';
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE IF NOT EXISTS {$table} (
            id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            migration varchar(255) NOT NULL,
            batch int(11) NOT NULL DEFAULT 0,
            executed_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
            rolled_back_at datetime DEFAULT NULL,
            execution_time_ms int(11) DEFAULT NULL,
            status enum('pending','running','completed','failed','rolled_back') DEFAULT 'pending',
            error_message text DEFAULT NULL,
            PRIMARY KEY (id),
            UNIQUE KEY migration (migration),
            KEY batch (batch),
            KEY status (status),
            KEY executed_at (executed_at)
        ) {$charset_collate};";

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);

        // Log installation
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('FleekDash: Migrations tracking table installed');
        }
    }

    /**
     * Check if migrations table exists
     */
    public static function exists(): bool
    {
        global $wpdb;
        $table = $wpdb->prefix . 'fleekdash_migrations';

        return $wpdb->get_var($wpdb->prepare(
            "SHOW TABLES LIKE %s",
            $table
        )) === $table;
    }

    /**
     * Uninstall migrations table
     */
    public static function uninstall(): void
    {
        global $wpdb;
        $table = $wpdb->prefix . 'fleekdash_migrations';
        $wpdb->query("DROP TABLE IF EXISTS {$table}");

        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('FleekDash: Migrations tracking table uninstalled');
        }
    }
}
