<?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 Queue Workers Tabelle
 */
final readonly class CreateQueueWorkersTable implements Migration
{
    public function up(ConnectionInterface $connection): void
    {
        $schema = new Schema($connection);

        $schema->createIfNotExists('queue_workers', function ($table) {
            // Primary Key - Worker ID (Hash basiert auf hostname + PID + Timestamp)
            $table->string('id', 32)->primary();

            // Worker Identification
            $table->string('hostname', 255);
            $table->integer('process_id');
            $table->string('version', 20)->default('1.0.0');

            // Queue Configuration
            $table->json('queues')->comment('Queues that this worker handles');
            $table->integer('max_jobs')->default(10)->comment('Maximum concurrent jobs');
            $table->integer('current_jobs')->default(0)->comment('Currently running jobs');

            // Worker Status
            $table->boolean('is_active')->default(true);
            $table->timestamp('registered_at')->default('CURRENT_TIMESTAMP');
            $table->timestamp('last_heartbeat')->nullable();

            // Performance Metrics
            $table->decimal('cpu_usage', 5, 2)->default(0)->comment('CPU usage percentage (0-100)');
            $table->bigInteger('memory_usage_bytes')->default(0)->comment('Memory usage in bytes');

            // Worker Capabilities
            $table->json('capabilities')->nullable()->comment('Worker capabilities/features');

            // Indexes
            $table->index(['hostname', 'process_id'], 'idx_worker_host_process');
            $table->index(['is_active', 'last_heartbeat'], 'idx_worker_active_heartbeat');
            $table->index('last_heartbeat', 'idx_worker_heartbeat');
            $table->index('current_jobs', 'idx_worker_current_jobs');
        });

        $schema->execute();
    }

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

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

    public function getDescription(): string
    {
        return 'Create queue_workers table for distributed job processing';
    }

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