<?php

declare(strict_types=1);

namespace CloudXM\NFe\Persistence\Migrations;

use CloudXM\SDK\Support\HasLogger;
use CloudXM\SDK\Contracts\MigrationInterface;

class AddEmissionsV2Columns010 implements MigrationInterface
{
    use HasLogger;

    private string $table_prefix;

    public function __construct(string $table_prefix)
    {
        $this->table_prefix = $table_prefix;
    }

    public function run(): bool
    {
        global $wpdb;

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

        $protocol_exists = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS 
                 WHERE TABLE_SCHEMA = DATABASE() 
                 AND TABLE_NAME = %s 
                 AND COLUMN_NAME = 'protocol'",
                $table_name
            )
        );

        if (!$protocol_exists) {
            $wpdb->query(
                "ALTER TABLE {$table_name} 
                 ADD COLUMN protocol varchar(15) DEFAULT NULL 
                 AFTER protocol_number"
            );
            $changes['protocol'] = 'added varchar(15) after protocol_number';
        }

        $issued_at_exists = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS 
                 WHERE TABLE_SCHEMA = DATABASE() 
                 AND TABLE_NAME = %s 
                 AND COLUMN_NAME = 'issued_at'",
                $table_name
            )
        );

        if (!$issued_at_exists) {
            $wpdb->query(
                "ALTER TABLE {$table_name} 
                 ADD COLUMN issued_at datetime DEFAULT NULL 
                 AFTER emission_date"
            );
            $changes['issued_at'] = 'added datetime after emission_date';
        }

        $this->log()->debug('nfe.migration_completed', [
            'migration' => '010_add_emissions_v2_columns',
            'version' => '2.14.1',
            'operation' => 'add_v2_columns',
            'table' => $table_name,
            'changes' => $changes,
            'timing' => date('Y-m-d H:i:s')
        ]);

        return true;
    }

    public function rollback(): bool
    {
        global $wpdb;

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

        $this->log()->debug('nfe.migration_rolled_back', [
            'migration' => '010_add_emissions_v2_columns',
            'operation' => 'rollback_v2_columns'
        ]);

        return true;
    }

    public function getDescription(): string
    {
        return 'Add protocol and issued_at columns to NFe emissions table for v2 API backward compatibility';
    }

    public function getVersion(): string
    {
        return '2.14.1';
    }
}
