<?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 CreateDeadLetterJobsTable implements Migration
{
    public function up(ConnectionInterface $connection): void
    {
        $schema = new Schema($connection);

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

            // Job references
            $table->string('original_job_id', 26)->index();
            $table->string('dead_letter_queue', 100)->index();
            $table->string('original_queue', 50)->index();

            // Job data
            $table->text('job_payload');

            // Failure information
            $table->text('failure_reason');
            $table->string('exception_type', 255)->nullable();
            $table->longText('stack_trace')->nullable();

            // Attempt tracking
            $table->integer('failed_attempts');
            $table->integer('retry_count')->default(0);

            // Timestamps
            $table->timestamp('failed_at')->index();
            $table->timestamp('moved_to_dlq_at')->index();
            $table->timestamp('last_retry_at')->nullable();

            // Composite indexes for efficient querying
            $table->index(['dead_letter_queue', 'moved_to_dlq_at']);
            $table->index(['original_queue', 'failed_at']);
            $table->index(['retry_count', 'last_retry_at']);
        });

        $schema->execute();
    }

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

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

    public function getDescription(): string
    {
        return "Create Dead Letter Jobs Table";
    }

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