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

        $schema->createIfNotExists('job_history', function ($table) {
            // Auto-incrementing primary key
            $table->id();

            // Job reference
            $table->string('job_id', 26)->index();

            // Status transition
            $table->string('old_status', 20)->nullable();
            $table->string('new_status', 20)->index();

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

            // Timestamp
            $table->timestamp('changed_at')->index();

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

            // Composite indexes for efficient querying
            $table->index(['job_id', 'changed_at']);
        });

        $schema->execute();
    }

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

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

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

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