<?php
/**
 * Migration: Create NFe Emissions Table
 *
 * Creates nfe_emissions table to store NFe invoice emission records
 *
 * @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 Emissions Table
 */
class CreateNfeEmissionsTable 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 emissions table
        $emissions_table = $wpdb->prefix . $this->table_prefix . 'emissions';
        $emissions_sql = "CREATE TABLE {$emissions_table} (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            order_id bigint(20) NOT NULL,
            invoice_id varchar(255) DEFAULT NULL,
            access_key varchar(44) DEFAULT NULL,
            status varchar(50) NOT NULL DEFAULT 'pending',
            environment varchar(20) NOT NULL DEFAULT 'production',
            emission_date datetime DEFAULT NULL,
            cancellation_date datetime DEFAULT NULL,
            cancellation_reason text DEFAULT NULL,
            invoice_number varchar(9) DEFAULT NULL,
            invoice_series varchar(3) DEFAULT NULL,
            invoice_type varchar(2) DEFAULT NULL,
            operation_type varchar(2) DEFAULT NULL,
            finality varchar(2) DEFAULT NULL,
            consumer_type varchar(1) DEFAULT NULL,
            consumer_id varchar(14) DEFAULT NULL,
            consumer_name varchar(255) DEFAULT NULL,
            consumer_email varchar(255) DEFAULT NULL,
            consumer_phone varchar(20) DEFAULT NULL,
            consumer_address text DEFAULT NULL,
            consumer_neighborhood varchar(100) DEFAULT NULL,
            consumer_city varchar(100) DEFAULT NULL,
            consumer_state varchar(2) DEFAULT NULL,
            consumer_zipcode varchar(9) DEFAULT NULL,
            consumer_country varchar(2) DEFAULT NULL,
            items_total decimal(15,2) NOT NULL DEFAULT 0.00,
            discount_total decimal(15,2) NOT NULL DEFAULT 0.00,
            other_expenses decimal(15,2) NOT NULL DEFAULT 0.00,
            total_value decimal(15,2) NOT NULL DEFAULT 0.00,
            icms_total decimal(15,2) NOT NULL DEFAULT 0.00,
            ipi_total decimal(15,2) NOT NULL DEFAULT 0.00,
            iss_total decimal(15,2) NOT NULL DEFAULT 0.00,
            tax_total decimal(15,2) NOT NULL DEFAULT 0.00,
            payment_method varchar(50) DEFAULT NULL,
            payment_installments int(11) DEFAULT NULL,
            xml_path varchar(500) DEFAULT NULL,
            pdf_path varchar(500) DEFAULT NULL,
            protocol_number varchar(15) DEFAULT NULL,
            authorization_code varchar(15) DEFAULT NULL,
            authorization_date datetime DEFAULT NULL,
            cancellation_protocol varchar(15) DEFAULT NULL,
            cancellation_code varchar(4) DEFAULT NULL,
            error_message text DEFAULT NULL,
            retry_count int(11) NOT NULL DEFAULT 0,
            last_retry_at datetime DEFAULT NULL,
            api_response longtext DEFAULT NULL,
            processing_duration_ms int(11) DEFAULT NULL,
            replacement_for_id bigint(20) DEFAULT NULL,
            correction_reason text DEFAULT NULL,
            created_at timestamp DEFAULT CURRENT_TIMESTAMP,
            updated_at timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            UNIQUE KEY uk_order_active (order_id, status),
            KEY idx_order_id (order_id),
            KEY idx_invoice_id (invoice_id),
            KEY idx_access_key (access_key),
            KEY idx_status (status),
            KEY idx_environment (environment),
            KEY idx_emission_date (emission_date),
            KEY idx_cancellation_date (cancellation_date),
            KEY idx_consumer_id (consumer_id),
            KEY idx_replacement_for (replacement_for_id),
            KEY idx_created_at (created_at)
        ) {$charset_collate};";

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

        $this->log()->debug('nfe.migration_completed', [
            'migration' => '001_create_nfe_emissions_table',
            'version' => '2.0.0',
            'operation' => 'create_nfe_emissions_table',
            'table' => $emissions_table,
            'timing' => date('Y-m-d H:i:s')
        ]);

        return true;
    }

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

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

        $this->log()->debug('nfe.migration_rolled_back', [
            'migration' => '001_create_nfe_emissions_table',
            'operation' => 'drop_nfe_emissions_table'
        ]);

        return true;
    }

    /**
     * Get migration description
     */
    public function getDescription(): string
    {
        return 'Create NFe emissions table to store invoice emission records';
    }

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