<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('operation_runs', function (Blueprint $table) {
            $table->id();
            $table->foreignId('managed_environment_id')->constrained()->cascadeOnDelete();
            $table->foreignId('user_id')->nullable()->constrained()->nullOnDelete();
            $table->string('initiator_name');
            $table->string('type');
            $table->string('status');
            $table->string('outcome')->default('pending');
            $table->string('run_identity_hash');
            $table->jsonb('summary_counts')->default('{}');
            $table->jsonb('failure_summary')->default('[]');
            $table->jsonb('context')->default('{}');
            $table->timestamp('started_at')->nullable();
            $table->timestamp('completed_at')->nullable();
            $table->timestamps();

            $table->index(['managed_environment_id', 'type', 'created_at']);
            $table->index(['managed_environment_id', 'created_at']);
        });

        // Partial unique index for idempotency
        DB::statement("CREATE UNIQUE INDEX operation_runs_active_unique ON operation_runs (managed_environment_id, run_identity_hash) WHERE status IN ('queued', 'running')");
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('operation_runs');
    }
};
