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

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

            // Chain identification
            $table->string('chain_id', 26)->unique()->index();
            $table->string('name', 255)->index();

            // Chain configuration
            $table->json('job_ids'); // Array of job IDs in execution order
            $table->string('execution_mode', 20)->index(); // sequential, parallel, conditional
            $table->boolean('stop_on_failure')->default(true)->index();

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

            // Status tracking
            $table->string('status', 20)->default('pending')->index(); // pending, running, completed, failed
            $table->timestamp('started_at')->nullable()->index();
            $table->timestamp('completed_at')->nullable()->index();

            // Timestamps
            $table->timestamp('created_at')->index();
            $table->timestamp('updated_at');

            // Composite indexes for efficient querying
            $table->index(['status', 'created_at']);
            $table->index(['execution_mode', 'status']);
            $table->index(['stop_on_failure', 'status']);
            $table->index(['started_at', 'completed_at']);
        });

        $schema->execute();
    }

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

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

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

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