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

        $schema->createIfNotExists('job_index', function ($table) {
            // ULID primary key
            $table->string('job_id', 26)->primary();

            // Job status and metadata
            $table->string('status', 20)->index();
            $table->string('queue_type', 50)->index();
            $table->integer('priority')->index();
            $table->integer('attempts')->default(0);
            $table->integer('max_attempts')->default(3);

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

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

            // Composite indexes for efficient querying
            $table->index(['status', 'queue_type']);
            $table->index(['status', 'attempts', 'max_attempts']);
            $table->index(['status', 'completed_at']);
        });

        $schema->execute();
    }

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

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

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

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