<?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('restore_runs', function (Blueprint $table) {
            $table->string('idempotency_key', 64)->nullable()->after('status');
        });

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

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

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

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