<?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;

final readonly class CreateJobMetricsTable implements Migration
{
    public function up(ConnectionInterface $connection): void
    {
        $schema = new Schema($connection);

        $schema->createIfNotExists('job_metrics', function ($table) {
            // Primary key
            $table->string('id', 26)->primary();

            // Job identification
            $table->string('job_id', 26)->index();
            $table->string('queue_name', 100)->index();

            // Status and execution tracking
            $table->string('status', 20)->index(); // pending, running, completed, failed
            $table->integer('attempts')->default(0)->index();
            $table->integer('max_attempts')->default(3);

            // Performance metrics
            $table->float('execution_time_ms')->default(0)->index();
            $table->integer('memory_usage_bytes')->default(0)->index();

            // Error tracking
            $table->text('error_message')->nullable();

            // Timestamps
            $table->timestamp('created_at')->index();
            $table->timestamp('updated_at');
            $table->timestamp('started_at')->nullable()->index();
            $table->timestamp('completed_at')->nullable()->index();
            $table->timestamp('failed_at')->nullable()->index();

            // Additional data
            $table->json('metadata')->nullable();

            // Composite indexes for efficient querying
            $table->index(['queue_name', 'status']);
            $table->index(['status', 'created_at']);
            $table->index(['job_id', 'attempts']);
            $table->index(['queue_name', 'completed_at']);
            $table->index(['queue_name', 'failed_at']);
            $table->index(['execution_time_ms', 'status']);
            $table->index(['memory_usage_bytes', 'status']);
            $table->index(['created_at', 'completed_at', 'status']); // For throughput calculations
        });

        $schema->execute();
    }

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

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

    public function getDescription(): string
    {
        return "Create Job Metrics Table";
    }

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