<?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')) {
            return;
        }

        Schema::table('findings', function (Blueprint $table) {
            if (! Schema::hasColumn('findings', 'evidence_fidelity')) {
                $table->string('evidence_fidelity')->nullable()->after('evidence_jsonb');
            }
        });

        if (Schema::hasColumn('findings', 'evidence_fidelity')) {
            DB::table('findings')
                ->whereNull('evidence_fidelity')
                ->update(['evidence_fidelity' => 'meta']);
        }

        Schema::table('findings', function (Blueprint $table) {
            if (! Schema::hasColumn('findings', 'evidence_fidelity')) {
                return;
            }

            $table->index(['managed_environment_id', 'evidence_fidelity'], 'findings_tenant_evidence_fidelity_idx');
        });
    }

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

        Schema::table('findings', function (Blueprint $table) {
            if (Schema::hasColumn('findings', 'evidence_fidelity')) {
                $table->dropIndex('findings_tenant_evidence_fidelity_idx');
                $table->dropColumn('evidence_fidelity');
            }
        });
    }
};
