<?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
    {
        if (Schema::hasTable('findings')) {
            DB::statement('DROP INDEX IF EXISTS findings_managed_environment_id_baseline_run_id_index');
            DB::statement('DROP INDEX IF EXISTS findings_managed_environment_id_current_run_id_index');
            DB::statement('DROP INDEX IF EXISTS findings_tenant_id_baseline_run_id_index');
            DB::statement('DROP INDEX IF EXISTS findings_tenant_id_current_run_id_index');

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

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

        if (Schema::hasTable('inventory_items')) {
            Schema::table('inventory_items', function (Blueprint $table) {
                if (Schema::hasColumn('inventory_items', 'last_seen_run_id')) {
                    $table->dropConstrainedForeignId('last_seen_run_id');
                }
            });
        }
    }

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

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

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

        if (Schema::hasTable('inventory_items')) {
            Schema::table('inventory_items', function (Blueprint $table) {
                if (! Schema::hasColumn('inventory_items', 'last_seen_run_id')) {
                    $table->foreignId('last_seen_run_id')
                        ->nullable()
                        ->after('last_seen_at')
                        ->constrained('inventory_sync_runs')
                        ->nullOnDelete();
                }
            });
        }
    }
};
