<?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('evidence_snapshot_items', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('evidence_snapshot_id')->constrained('evidence_snapshots')->cascadeOnDelete();
            $table->foreignId('workspace_id')->constrained('workspaces')->cascadeOnDelete();
            $table->foreignId('managed_environment_id')->constrained('managed_environments')->cascadeOnDelete();
            $table->string('dimension_key');
            $table->string('state')->default('missing');
            $table->boolean('required')->default(true);
            $table->string('source_kind');
            $table->string('source_record_type')->nullable();
            $table->string('source_record_id')->nullable();
            $table->string('source_fingerprint', 64)->nullable();
            $table->timestampTz('measured_at')->nullable();
            $table->timestampTz('freshness_at')->nullable();
            $table->jsonb('summary_payload')->default('{}');
            $table->unsignedInteger('sort_order')->default(0);
            $table->timestamps();

            $table->unique(['evidence_snapshot_id', 'dimension_key']);
            $table->index(['workspace_id', 'managed_environment_id', 'dimension_key']);
            $table->index(['managed_environment_id', 'state']);
        });

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

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