<?php
/**
 * Migration: Add user_agent column to history table
 *
 * Adds missing user_agent column for tracking user agent information
 *
 * @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: Add user_agent column to history table
 */
class AddUserAgentToHistoryTable 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 . 'history';

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

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

        if (!$column_exists) {
            $wpdb->query(
                "ALTER TABLE {$table_name} 
                 ADD COLUMN user_agent varchar(255) DEFAULT NULL 
                 AFTER ip_address"
            );
        }

        $this->log()->debug('nfe.migration_completed', [
            'migration' => '005_add_user_agent_to_history_table',
            'version' => '2.0.0',
            'operation' => 'add_user_agent_column',
            'table' => $table_name,
            'column_added' => $column_exists ? 'already_exists' : 'added',
            '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 . 'history';

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

        $this->log()->debug('nfe.migration_rolled_back', [
            'migration' => '005_add_user_agent_to_history_table',
            'operation' => 'drop_user_agent_column'
        ]);

        return true;
    }

    /**
     * Get migration description
     */
    public function getDescription(): string
    {
        return 'Add user_agent column to history table for tracking user agent information';
    }

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