<?php
/**
 * Migration: Create NFe Migrations Table
 *
 * Creates nfe_migrations table to track executed migrations
 *
 * @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 Migrations Table
 */
class CreateNfeMigrationsTable implements MigrationInterface
{
    use HasLogger;

    private string $table_prefix;

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

    /**
     * Run the migration
     */
    public function run(): bool
    {
        global $wpdb;

        $charset_collate = $wpdb->get_charset_collate();

        // Create migrations table
        $migrations_table = $wpdb->prefix . $this->table_prefix . 'migrations';
        $migrations_sql = "CREATE TABLE {$migrations_table} (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            migration varchar(255) NOT NULL,
            batch int(11) UNSIGNED NOT NULL,
            executed_at timestamp DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            UNIQUE KEY migration_batch_unique (migration, batch),
            KEY idx_migration (migration),
            KEY idx_batch (batch)
        ) {$charset_collate};";

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

        $this->log()->debug('nfe.migration_completed', [
            'migration' => '000_create_nfe_migrations_table',
            'version' => '2.0.0',
            'operation' => 'create_nfe_migrations_table',
            'table' => $migrations_table,
            'timing' => date('Y-m-d H:i:s')
        ]);

        return true;
    }

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

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

        $this->log()->debug('nfe.migration_rolled_back', [
            'migration' => '000_create_nfe_migrations_table',
            'operation' => 'drop_nfe_migrations_table'
        ]);

        return true;
    }

    /**
     * Get migration description
     */
    public function getDescription(): string
    {
        return 'Create migrations tracking table for NFe plugin';
    }

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