<?php

declare(strict_types=1);

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::create('finding_exception_evidence_references', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('finding_exception_id')->constrained('finding_exceptions')->cascadeOnDelete();
            $table->foreignId('workspace_id')->constrained('workspaces')->cascadeOnDelete();
            $table->foreignId('managed_environment_id')->constrained('managed_environments')->cascadeOnDelete();
            $table->string('source_type');
            $table->string('source_id')->nullable();
            $table->string('source_fingerprint')->nullable();
            $table->string('label');
            $table->jsonb('summary_payload')->default('{}');
            $table->timestampTz('measured_at')->nullable();
            $table->timestamps();

            $table->index(['finding_exception_id', 'source_type'], 'finding_exception_evidence_refs_parent_idx');
            $table->index(['workspace_id', 'managed_environment_id'], 'finding_exception_evidence_refs_scope_idx');
            $table->index(['managed_environment_id', 'source_type'], 'finding_exception_evidence_refs_source_idx');

            $table
                ->foreign(['managed_environment_id', 'workspace_id'], 'finding_exception_evidence_refs_environment_workspace_fk')
                ->references(['id', 'workspace_id'])
                ->on('managed_environments')
                ->cascadeOnDelete();
        });

        if (DB::getDriverName() === 'pgsql') {
            DB::statement('CREATE INDEX finding_exception_evidence_refs_payload_gin ON finding_exception_evidence_references USING GIN (summary_payload)');
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('finding_exception_evidence_references');
    }
};
