<?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_snapshots', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('workspace_id')->constrained('workspaces')->cascadeOnDelete();
            $table->foreignId('managed_environment_id')->constrained('managed_environments')->cascadeOnDelete();
            $table->foreignId('operation_run_id')->nullable()->constrained('operation_runs')->nullOnDelete();
            $table->foreignId('initiated_by_user_id')->nullable()->constrained('users')->nullOnDelete();
            $table->string('fingerprint', 64)->nullable();
            $table->string('previous_fingerprint', 64)->nullable();
            $table->string('status')->default('queued');
            $table->string('completeness_state')->default('missing');
            $table->jsonb('summary')->default('{}');
            $table->timestampTz('generated_at')->nullable();
            $table->timestampTz('expires_at')->nullable();
            $table->timestamps();

            $table->index(['workspace_id', 'managed_environment_id', 'created_at']);
            $table->index(['managed_environment_id', 'status', 'generated_at']);
            $table->index(['status', 'expires_at']);
        });

        DB::statement("CREATE UNIQUE INDEX evidence_snapshots_active_unique ON evidence_snapshots (workspace_id, managed_environment_id) WHERE status = 'active'");
        DB::statement("CREATE UNIQUE INDEX evidence_snapshots_fingerprint_unique ON evidence_snapshots (workspace_id, managed_environment_id, fingerprint) WHERE fingerprint IS NOT NULL AND status NOT IN ('expired', 'failed')");
    }

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