<?php
/**
 * Migration: Create NFe Queue Table
 *
 * Creates nfe_queue table to manage NFe processing queue
 *
 * @package CloudXM\NFe\Persistence\Migrations
 * @since 2.0.0
 */

declare(strict_types=1);

namespace CloudXM\NFe\Persistence\Migrations;

use CloudXM\SDK\Support\HasLogger;
use CloudXM\SDK\Contracts\MigrationInterface;

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Migration: Create NFe Queue Table
 */
class CreateNfeQueueTable implements MigrationInterface
{
    use HasLogger;

    private string $table_prefix;

    /**
     * Constructor
     */
    public function __construct(string $table_prefix)
    {
        $this->table_prefix = $table_prefix;
    }

    /**
     * Run migration
     */
    public function run(): bool
    {
        global $wpdb;

        $charset_collate = $wpdb->get_charset_collate();

        // Create queue table
        $queue_table = $wpdb->prefix . $this->table_prefix . 'queue';
        $queue_sql = "CREATE TABLE {$queue_table} (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            order_id bigint(20) NOT NULL,
            task_type varchar(50) NOT NULL,
            status varchar(50) NOT NULL DEFAULT 'pending',
            priority int(11) NOT NULL DEFAULT 10,
            attempts int(11) NOT NULL DEFAULT 0,
            max_attempts int(11) NOT NULL DEFAULT 3,
            error_message text DEFAULT NULL,
            payload longtext DEFAULT NULL,
            result longtext DEFAULT NULL,
            scheduled_at datetime DEFAULT NULL,
            started_at datetime DEFAULT NULL,
            completed_at datetime DEFAULT NULL,
            created_at timestamp DEFAULT CURRENT_TIMESTAMP,
            updated_at timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY idx_order_id (order_id),
            KEY idx_task_type (task_type),
            KEY idx_status (status),
            KEY idx_priority (priority),
            KEY idx_scheduled_at (scheduled_at),
            KEY idx_status_priority (status, priority),
            KEY idx_created_at (created_at)
        ) {$charset_collate};";

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

        $this->log()->debug('nfe.migration_completed', [
            'migration' => '002_create_nfe_queue_table',
            'version' => '2.0.0',
            'operation' => 'create_nfe_queue_table',
            'table' => $queue_table,
            'timing' => date('Y-m-d H:i:s')
        ]);

        return true;
    }

    /**
     * Rollback migration
     */
    public function rollback(): bool
    {
        global $wpdb;

        $table_name = $this->table_prefix . 'queue';
        $full_table_name = $wpdb->prefix . $table_name;
        $wpdb->query("DROP TABLE IF EXISTS {$full_table_name}");

        $this->log()->debug('nfe.migration_rolled_back', [
            'migration' => '002_create_nfe_queue_table',
            'operation' => 'drop_nfe_queue_table'
        ]);

        return true;
    }

    /**
     * Get migration description
     */
    public function getDescription(): string
    {
        return 'Create NFe queue table to manage processing queue';
    }

    /**
     * Get migration version
     */
    public function getVersion(): string
    {
        return '2.0.0';
    }
}
