<?php
/**
 * Migration: Add v2 API Fields to NFe Emissions Table
 *
 * Adds new fields required for v2 API responses:
 * - processing_strategy: How the invoice was processed (synchronous, asynchronous, debug)
 * - allowed_actions: JSON array of allowed operations (cancel, pdf, xml)
 * - created_at: Invoice creation timestamp from API
 *
 * @package CloudXM\NFe\Persistence\Migrations
 * @since 3.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: Add v2 Fields to Emissions Table
 */
class AddV2FieldsToEmissionsTable 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;

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

        // Add processing_strategy 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 = 'processing_strategy'",
                $table_name
            )
        );

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

        // Add allowed_actions 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 = 'allowed_actions'",
                $table_name
            )
        );

        if (!$column_exists) {
            $wpdb->query(
                "ALTER TABLE {$table_name} 
                 ADD COLUMN allowed_actions JSON DEFAULT NULL 
                 AFTER processing_strategy"
            );
        }

        // Add created_at 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 = 'created_at'",
                $table_name
            )
        );

        if (!$column_exists) {
            $wpdb->query(
                "ALTER TABLE {$table_name} 
                 ADD COLUMN created_at datetime DEFAULT NULL 
                 AFTER updated_at"
            );
        }

        $this->log()->debug('nfe.migration_completed', [
            'migration' => '006_add_v2_fields_to_emissions_table',
            'version' => '3.0.0',
            'operation' => 'add_v2_fields',
            'table' => $table_name,
            'changes' => [
                'processing_strategy' => 'added varchar(20)',
                'allowed_actions' => 'added JSON',
                'created_at' => 'added datetime'
            ],
            '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';

        // Remove v2 columns
        $wpdb->query(
            "ALTER TABLE {$table_name} 
             DROP COLUMN IF EXISTS processing_strategy,
             DROP COLUMN IF EXISTS allowed_actions,
             DROP COLUMN IF EXISTS created_at"
        );

        $this->log()->debug('nfe.migration_rolled_back', [
            'migration' => '006_add_v2_fields_to_emissions_table',
            'operation' => 'rollback_v2_fields'
        ]);

        return true;
    }

    /**
     * Get migration description
     */
    public function getDescription(): string
    {
        return 'Add v2 API fields to NFe emissions table: processing_strategy, allowed_actions, created_at';
    }

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