<?php
/**
 * Migration: Alter NFe Emissions Table - Fix access_key and add dps_number
 *
 * - Change access_key from varchar(44) to varchar(50) to accommodate actual NFe access keys
 * - Add dps_number column that was missing from original migration
 *
 * @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: Alter NFe Emissions Table
 */
class AlterNfeEmissionsTableAccessKey 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();
        $table_name = $wpdb->prefix . $this->table_prefix . 'emissions';

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

        // Alter access_key column from varchar(44) to varchar(50)
        $wpdb->query(
            "ALTER TABLE {$table_name} 
             MODIFY COLUMN access_key varchar(50) DEFAULT NULL"
        );

        // Add dps_number column if it doesn't exist
        $column_exists = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS 
                 WHERE TABLE_SCHEMA = DATABASE() 
                 AND TABLE_NAME = %s 
                 AND COLUMN_NAME = 'dps_number'",
                $table_name
            )
        );

        if (!$column_exists) {
            $wpdb->query(
                "ALTER TABLE {$table_name} 
                 ADD COLUMN dps_number varchar(20) DEFAULT NULL 
                 AFTER invoice_series"
            );
        }

        $this->log()->debug('nfe.migration_completed', [
            'migration' => '004_alter_nfe_emissions_table_access_key',
            'version' => '2.0.0',
            'operation' => 'alter_nfe_emissions_table',
            'table' => $table_name,
            'changes' => [
                'access_key' => 'varchar(44) -> varchar(50)',
                'dps_number' => 'added varchar(20)'
            ],
            'timing' => date('Y-m-d H:i:s')
        ]);

        return true;
    }

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

        $table_name = $wpdb->prefix . $this->table_prefix . 'emissions';

        // Revert access_key to varchar(44)
        $wpdb->query(
            "ALTER TABLE {$table_name} 
             MODIFY COLUMN access_key varchar(44) DEFAULT NULL"
        );

        // Remove dps_number column
        $wpdb->query(
            "ALTER TABLE {$table_name} 
             DROP COLUMN dps_number"
        );

        $this->log()->debug('nfe.migration_rolled_back', [
            'migration' => '004_alter_nfe_emissions_table_access_key',
            'operation' => 'rollback_alter_nfe_emissions_table'
        ]);

        return true;
    }

    /**
     * Get migration description
     */
    public function getDescription(): string
    {
        return 'Alter NFe emissions table: expand access_key to varchar(50) and add missing dps_number column';
    }

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