<?php

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

return new class extends Migration
{
    public function up(): void
    {
        if (! Schema::hasTable('findings') || ! Schema::hasTable('operation_runs')) {
            return;
        }

        Schema::table('findings', function (Blueprint $table) {
            if (! Schema::hasColumn('findings', 'baseline_operation_run_id')) {
                $table->foreignId('baseline_operation_run_id')
                    ->nullable()
                    ->after('baseline_run_id')
                    ->constrained('operation_runs')
                    ->nullOnDelete();
                $table->index(['managed_environment_id', 'baseline_operation_run_id'], 'findings_tenant_baseline_operation_run_idx');
            }

            if (! Schema::hasColumn('findings', 'current_operation_run_id')) {
                $table->foreignId('current_operation_run_id')
                    ->nullable()
                    ->after('current_run_id')
                    ->constrained('operation_runs')
                    ->nullOnDelete();
                $table->index(['managed_environment_id', 'current_operation_run_id'], 'findings_tenant_current_operation_run_idx');
            }
        });
    }

    public function down(): void
    {
        if (! Schema::hasTable('findings')) {
            return;
        }

        Schema::table('findings', function (Blueprint $table) {
            if (Schema::hasColumn('findings', 'baseline_operation_run_id')) {
                $table->dropIndex('findings_tenant_baseline_operation_run_idx');
                $table->dropConstrainedForeignId('baseline_operation_run_id');
            }

            if (Schema::hasColumn('findings', 'current_operation_run_id')) {
                $table->dropIndex('findings_tenant_current_operation_run_idx');
                $table->dropConstrainedForeignId('current_operation_run_id');
            }
        });
    }
};
