<?php

declare(strict_types=1);

namespace App\Framework\Deployment\Pipeline\Migrations;

use App\Framework\Database\ConnectionInterface;
use App\Framework\Database\Migration\Migration;
use App\Framework\Database\Migration\MigrationVersion;
use App\Framework\Database\Schema\Blueprint;
use App\Framework\Database\Schema\Schema;

/**
 * Create pipeline_history table for deployment tracking
 */
final readonly class CreatePipelineHistoryTable implements Migration
{
    public function up(ConnectionInterface $connection): void
    {
        $schema = new Schema($connection);

        $schema->createIfNotExists('pipeline_history', function (Blueprint $table) {
            // Primary identifier
            $table->string('pipeline_id', 26)->primary();

            // Environment and status
            $table->string('environment', 50);
            $table->string('status', 50);

            // Execution details
            $table->text('stages_data'); // Stage results as JSON
            $table->integer('total_duration_ms');
            $table->text('error')->nullable();

            // Rollback information
            $table->boolean('was_rolled_back')->default(false);
            $table->string('failed_stage', 50)->nullable();

            // Timestamps
            $table->timestamp('started_at')->useCurrent();
            $table->timestamp('completed_at')->nullable();

            // Indexes for querying
            $table->index(['environment', 'status'], 'idx_pipeline_history_env_status');
            $table->index(['completed_at'], 'idx_pipeline_history_completed');
        });

        $schema->execute();
    }

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

    public function getVersion(): MigrationVersion
    {
        return MigrationVersion::fromTimestamp('2024_12_19_180000');
    }

    public function getDescription(): string
    {
        return 'Create pipeline_history table for deployment tracking';
    }
}
