<?php
namespace FleekDash\CLI;

use FleekDash\Database\Core\MigrationManager;

defined('ABSPATH') || exit;

/**
 * Migration CLI Commands for WP-CLI
 *
 * Provides command-line interface for managing migrations
 */
class MigrationCommands
{
    private $manager;

    public function __construct()
    {
        $this->manager = new MigrationManager();
    }

    /**
     * Run pending migrations
     *
     * ## EXAMPLES
     *
     *     wp fleekdash migration:run
     *
     * @when after_wp_load
     */
    public function run($args, $assoc_args)
    {
        \WP_CLI::line('Running migrations...');

        $results = $this->manager->run();

        if (isset($results['message'])) {
            \WP_CLI::success($results['message']);
            return;
        }

        \WP_CLI::line('');
        foreach ($results['migrations'] as $result) {
            if ($result['success']) {
                \WP_CLI::success(
                    sprintf(
                        '✓ %s (%.0fms)',
                        $result['migration'],
                        $result['time']
                    )
                );
            } else {
                \WP_CLI::error($result['migration'] . ': ' . $result['error'], false);
                \WP_CLI::line('');
                \WP_CLI::line('Stack trace:');
                \WP_CLI::line($result['trace']);
            }
        }

        if (isset($results['stopped'])) {
            \WP_CLI::error('Migrations stopped due to failure');
        }

        \WP_CLI::line('');
        \WP_CLI::success('Migrations complete!');
    }

    /**
     * Rollback last migration batch
     *
     * ## OPTIONS
     *
     * [--steps=<steps>]
     * : Number of batches to rollback
     * ---
     * default: 1
     * ---
     *
     * ## EXAMPLES
     *
     *     wp fleekdash migration:rollback
     *     wp fleekdash migration:rollback --steps=2
     *
     * @when after_wp_load
     */
    public function rollback($args, $assoc_args)
    {
        $steps = isset($assoc_args['steps']) ? (int)$assoc_args['steps'] : 1;

        \WP_CLI::line("Rolling back {$steps} batch(es)...");

        $results = $this->manager->rollback($steps);

        if (isset($results['message'])) {
            \WP_CLI::line($results['message']);
            return;
        }

        \WP_CLI::line('');
        foreach ($results['rolled_back'] as $result) {
            if ($result['success']) {
                \WP_CLI::success('✓ Rolled back: ' . $result['migration']);
            } else {
                \WP_CLI::error($result['migration'] . ': ' . $result['error'], false);
            }
        }

        \WP_CLI::line('');
        \WP_CLI::success('Rollback complete!');
    }

    /**
     * Show migration status
     *
     * ## EXAMPLES
     *
     *     wp fleekdash migration:status
     *
     * @when after_wp_load
     */
    public function status($args, $assoc_args)
    {
        $status = $this->manager->status();

        \WP_CLI::line('');
        \WP_CLI::line('Migration Status:');
        \WP_CLI::line("  Total:    {$status['total']}");
        \WP_CLI::line("  Executed: {$status['executed']}");
        \WP_CLI::line("  Pending:  {$status['pending']}");
        \WP_CLI::line("  Failed:   {$status['failed']}");

        if ($status['last_batch']) {
            \WP_CLI::line("  Last Batch: {$status['last_batch']}");
        }

        if (!empty($status['migrations']['pending'])) {
            \WP_CLI::line('');
            \WP_CLI::line('Pending Migrations:');
            foreach ($status['migrations']['pending'] as $migration) {
                \WP_CLI::line("  • {$migration}");
            }
        }

        if (!empty($status['migrations']['failed'])) {
            \WP_CLI::line('');
            \WP_CLI::line('Failed Migrations:');
            foreach ($status['migrations']['failed'] as $failed) {
                \WP_CLI::error("  ✗ {$failed['migration']}: {$failed['error_message']}", false);
            }
        }

        \WP_CLI::line('');
    }

    /**
     * Reset all migrations (rollback everything)
     *
     * ## EXAMPLES
     *
     *     wp fleekdash migration:reset
     *
     * @when after_wp_load
     */
    public function reset($args, $assoc_args)
    {
        if (!isset($assoc_args['yes'])) {
            \WP_CLI::line('This will rollback ALL migrations.');
            \WP_CLI::line('Use --yes to confirm.');
            return;
        }

        \WP_CLI::line('Resetting all migrations...');

        $results = $this->manager->reset();

        \WP_CLI::line('');
        foreach ($results['rolled_back'] as $result) {
            if ($result['success']) {
                \WP_CLI::success('✓ Rolled back: ' . $result['migration']);
            } else {
                \WP_CLI::error($result['migration'] . ': ' . $result['error'], false);
            }
        }

        \WP_CLI::line('');
        \WP_CLI::success('Reset complete!');
    }

    /**
     * Refresh migrations (reset + run)
     *
     * ## EXAMPLES
     *
     *     wp fleekdash migration:refresh
     *
     * @when after_wp_load
     */
    public function refresh($args, $assoc_args)
    {
        if (!isset($assoc_args['yes'])) {
            \WP_CLI::line('This will reset and re-run ALL migrations.');
            \WP_CLI::line('Use --yes to confirm.');
            return;
        }

        \WP_CLI::line('Refreshing migrations...');
        \WP_CLI::line('');

        // Reset
        $this->reset($args, ['yes' => true]);

        \WP_CLI::line('');

        // Run
        $this->run($args, $assoc_args);
    }

    /**
     * Check database health
     *
     * ## EXAMPLES
     *
     *     wp fleekdash db:health
     *
     * @when after_wp_load
     */
    public function health($args, $assoc_args)
    {
        $health = $this->manager->health();

        \WP_CLI::line('');
        \WP_CLI::line('Database Health Check:');
        \WP_CLI::line("  Overall Status: {$health['status']}");
        \WP_CLI::line('');
        \WP_CLI::line('Checks:');

        foreach ($health['checks'] as $name => $check) {
            $icon = $check['status'] === 'pass' ? '✓' : '✗';
            $method = $check['status'] === 'pass' ? 'success' : 'error';

            \WP_CLI::{$method}("  {$icon} {$check['message']}");
        }

        \WP_CLI::line('');
    }
}
