<?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_decisions', 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->foreignId('actor_user_id')->constrained('users');
            $table->string('decision_type');
            $table->text('reason')->nullable();
            $table->timestampTz('effective_from')->nullable();
            $table->timestampTz('expires_at')->nullable();
            $table->jsonb('metadata')->default('{}');
            $table->timestampTz('decided_at');
            $table->timestamps();

            $table->index(['finding_exception_id', 'decided_at'], 'finding_exception_decisions_history_idx');
            $table->index(['workspace_id', 'managed_environment_id', 'decision_type'], 'finding_exception_decisions_scope_type_idx');
            $table->index(['managed_environment_id', 'actor_user_id'], 'finding_exception_decisions_actor_idx');

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

        Schema::table('finding_exceptions', function (Blueprint $table): void {
            $table
                ->foreign('current_decision_id')
                ->references('id')
                ->on('finding_exception_decisions')
                ->nullOnDelete();
        });

        if (DB::getDriverName() === 'pgsql') {
            DB::statement('CREATE INDEX finding_exception_decisions_metadata_gin ON finding_exception_decisions USING GIN (metadata)');
        }
    }

    public function down(): void
    {
        Schema::table('finding_exceptions', function (Blueprint $table): void {
            $table->dropForeign(['current_decision_id']);
        });

        Schema::dropIfExists('finding_exception_decisions');
    }
};
