<?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;

/**
 * Create job_batches table for batch job tracking
 */
final class Migration_2024_10_02_140000_CreateJobBatchesTable implements Migration
{
    public function up(ConnectionInterface $connection): void
    {
        $schema = new Schema($connection);

        $schema->createIfNotExists('job_batches', function ($table) {
            // Primary identification
            $table->string('batch_id', 64)->primary();
            $table->string('name', 255);

            // Job tracking
            $table->json('job_ids');
            $table->string('status', 20)->default('pending')->index();
            $table->integer('total_jobs')->default(0);
            $table->integer('processed_jobs')->default(0);
            $table->integer('failed_jobs')->default(0);

            // Configuration and metadata
            $table->json('options')->nullable();

            // Timestamps for lifecycle tracking
            $table->timestamp('created_at')->default('CURRENT_TIMESTAMP');
            $table->timestamp('started_at')->nullable();
            $table->timestamp('completed_at')->nullable();
            $table->timestamp('failed_at')->nullable();
            $table->timestamp('cancelled_at')->nullable();

            // Indexes for efficient querying
            $table->index(['status', 'created_at']);
            $table->index('created_at');
            $table->index(['status', 'total_jobs']);
        });

        $schema->execute();
    }

    public function down(ConnectionInterface $connection): void
    {
        $schema = new Schema($connection);

        $schema->dropIfExists('job_batches');

        $schema->execute();
    }

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

    public function getDescription(): string
    {
        return 'Create job_batches table for tracking batch job processing';
    }
}
