<?php

declare(strict_types=1);

namespace App\Framework\Queue\Migrations;

use App\Framework\Database\ConnectionInterface;
use App\Framework\Database\Migration\Migration;
use App\Framework\Database\Migration\MigrationVersion;
use App\Framework\Database\Schema\Schema;

/**
 * Migration für Failover Events Tabelle
 */
final readonly class CreateFailoverEventsTable implements Migration
{
    public function up(ConnectionInterface $connection): void
    {
        $schema = new Schema($connection);

        $schema->createIfNotExists('failover_events', function ($table) {
            // Auto-incrementing ID
            $table->id();

            // Job der betroffen war
            $table->string('job_id', 32);

            // Worker die beim Failover beteiligt waren
            $table->string('failed_worker_id', 32);
            $table->string('new_worker_id', 32)->nullable();

            // Event Typ
            $table->enum('event_type', [
                'worker_failure',
                'job_reassignment',
                'recovery_completed',
                'manual_failover',
            ]);

            // Zusätzliche Event-Daten
            $table->json('event_data')->nullable()->comment('Additional failover context and metrics');

            // Timestamps
            $table->timestamp('failover_at')->default('CURRENT_TIMESTAMP');

            // Indexes
            $table->index('job_id', 'idx_failover_job');
            $table->index('failed_worker_id', 'idx_failover_failed_worker');
            $table->index('new_worker_id', 'idx_failover_new_worker');
            $table->index('event_type', 'idx_failover_event_type');
            $table->index('failover_at', 'idx_failover_time');
            $table->index(['failed_worker_id', 'failover_at'], 'idx_failover_worker_time');
        });

        $schema->execute();
    }

    public function down(ConnectionInterface $connection): void
    {
        $schema = new Schema($connection);
        $schema->dropIfExists('failover_events');
        $schema->execute();
    }

    public function getVersion(): MigrationVersion
    {
        return MigrationVersion::fromTimestamp("2024_12_19_151000");
    }

    public function getDescription(): string
    {
        return 'Create failover_events table for tracking worker failover and recovery events';
    }

    public function getDomain(): string
    {
        return "Framework";
    }
}
