<?php
/**
 * Migration: Create NFe History Table
 *
 * Creates nfe_history table to track all NFe events and operations
 *
 * @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 History Table
 */
class CreateNfeHistoryTable 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 history table
        $history_table = $wpdb->prefix . $this->table_prefix . 'history';
        $history_sql = "CREATE TABLE {$history_table} (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            emission_id bigint(20) NOT NULL,
            event_type varchar(50) NOT NULL,
            event_status varchar(50) NOT NULL,
            event_message text DEFAULT NULL,
            event_data longtext DEFAULT NULL,
            user_id bigint(20) DEFAULT NULL,
            ip_address varchar(45) DEFAULT NULL,
            created_at timestamp DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY idx_emission_id (emission_id),
            KEY idx_event_type (event_type),
            KEY idx_event_status (event_status),
            KEY idx_created_at (created_at),
            KEY idx_emission_created (emission_id, created_at)
        ) {$charset_collate};";

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

        $this->log()->debug('nfe.migration_completed', [
            'migration' => '003_create_nfe_history_table',
            'version' => '2.0.0',
            'operation' => 'create_nfe_history_table',
            'table' => $history_table,
            'timing' => date('Y-m-d H:i:s')
        ]);

        return true;
    }

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

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

        $this->log()->debug('nfe.migration_rolled_back', [
            'migration' => '003_create_nfe_history_table',
            'operation' => 'drop_nfe_history_table'
        ]);

        return true;
    }

    /**
     * Get migration description
     */
    public function getDescription(): string
    {
        return 'Create NFe history table to track all events and operations';
    }

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