<?php

namespace ZenoChatbot\Framework\Database\Migration;

/**
 * Simple Migration Runner
 *
 * Runs all migration files from a given path without tracking
 */
class Migrator
{
    /**
     * Run all migrations from the given path
     */
    public static function migrate($path)
    {


        if (!is_dir($path)) {
            return false;
        }

        // Get all migration files

        $files = glob($path . '/*.php');

        if (empty($files)) {
            return true;
        }


        // Sort files to ensure consistent execution order
        sort($files);

        foreach ($files as $file) {
            static::runMigrationFile($file);
        }

        return true;
    }

    /**
     * Run a single migration file
     */
    protected static function runMigrationFile($file)
    {
        // Include the migration file and get the returned instance
        $migration = require $file;

        // Check if it's a migration instance
        if (!$migration || !static::isMigrationInstance($migration)) {
            return false;
        }

        // Run up method
        if (method_exists($migration, 'up')) {
            $result = $migration->up();

            // Execute the returned SQL if it's a Sql instance
            if ($result instanceof Sql) {
                static::executeSql($result);
            }
        }

        return true;
    }

    /**
     * Check if instance is a migration instance
     */
    protected static function isMigrationInstance($instance)
    {
        if (!is_object($instance)) {
            return false;
        }

        // Check if it's an instance of Migration class
        return $instance instanceof Migration;
    }

    /**
     * Execute SQL using WordPress dbDelta
     */
    protected static function executeSql(Sql $sql)
    {
        $sqlStatement = $sql->getSql();

        if (empty($sqlStatement)) {
            return false;
        }

        // Always use dbDelta for migrations
        if (!function_exists('dbDelta')) {
            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        }

        $result = dbDelta($sqlStatement);

        return $result;
    }
}
