<?php

declare(strict_types=1);

namespace CloudXM\NFe\Persistence\Migrations;

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

if (!defined('ABSPATH')) {
    exit;
}

class RemoveUniqueOrderStatusConstraint 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';

        $index_exists = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT COUNT(*) FROM INFORMATION_SCHEMA.STATISTICS
                 WHERE TABLE_SCHEMA = DATABASE()
                 AND TABLE_NAME = %s
                 AND INDEX_NAME = 'uk_order_active'",
                $table_name
            )
        );

        if ($index_exists) {
            $wpdb->query("ALTER TABLE {$table_name} DROP INDEX uk_order_active");
        }

        $this->log()->debug('nfe.migration_completed', [
            'migration' => '007_remove_unique_order_status_constraint',
            'version' => '3.1.0',
            'operation' => 'drop_unique_order_status',
            'table' => $table_name,
        ]);

        return true;
    }

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

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

        $wpdb->query("ALTER TABLE {$table_name} ADD UNIQUE KEY uk_order_active (order_id, status)");

        $this->log()->debug('nfe.migration_rolled_back', [
            'migration' => '007_remove_unique_order_status_constraint',
            'operation' => 'restore_unique_order_status',
        ]);

        return true;
    }

    public function getDescription(): string
    {
        return 'Remove UNIQUE constraint on (order_id, status) to allow multiple emissions per order';
    }

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