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

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

            // Job references
            $table->string('dependent_job_id', 26)->index();
            $table->string('depends_on_job_id', 26)->index();

            // Dependency configuration
            $table->string('dependency_type', 20)->index(); // completion, success, conditional
            $table->text('condition_expression')->nullable();

            // Status tracking
            $table->boolean('is_satisfied')->default(false)->index();
            $table->timestamp('satisfied_at')->nullable();

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

            // Composite indexes for efficient querying
            $table->index(['dependent_job_id', 'is_satisfied']);
            $table->index(['depends_on_job_id', 'dependency_type']);
            $table->index(['is_satisfied', 'satisfied_at']);
            $table->index(['dependency_type', 'created_at']);

            // Unique constraint to prevent duplicate dependencies
            $table->unique(['dependent_job_id', 'depends_on_job_id', 'dependency_type']);
        });

        $schema->execute();
    }

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

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

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

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