<?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
{
    public function up(): void
    {
        Schema::table('bulk_operation_runs', function (Blueprint $table) {
            $table->string('idempotency_key', 64)->nullable()->after('action');
        });

        Schema::table('bulk_operation_runs', function (Blueprint $table) {
            $table->index(['managed_environment_id', 'idempotency_key'], 'bulk_runs_tenant_idempotency');
        });

        DB::statement("CREATE UNIQUE INDEX bulk_runs_idempotency_active ON bulk_operation_runs (managed_environment_id, idempotency_key) WHERE idempotency_key IS NOT NULL AND status IN ('pending', 'running')");
    }

    public function down(): void
    {
        DB::statement('DROP INDEX IF EXISTS bulk_runs_idempotency_active');

        Schema::table('bulk_operation_runs', function (Blueprint $table) {
            $table->dropIndex('bulk_runs_tenant_idempotency');
            $table->dropColumn('idempotency_key');
        });
    }
};
