<?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('environment_reviews', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('workspace_id')->constrained('workspaces')->cascadeOnDelete();
            $table->foreignId('managed_environment_id')->constrained('managed_environments')->cascadeOnDelete();
            $table->foreignId('evidence_snapshot_id')->constrained('evidence_snapshots')->restrictOnDelete();
            $table->foreignId('current_export_review_pack_id')->nullable()->constrained('review_packs')->nullOnDelete();
            $table->foreignId('operation_run_id')->nullable()->constrained('operation_runs')->nullOnDelete();
            $table->foreignId('initiated_by_user_id')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignId('published_by_user_id')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignId('superseded_by_review_id')->nullable()->constrained('environment_reviews')->nullOnDelete();
            $table->string('fingerprint', 64)->nullable();
            $table->string('status')->default('draft');
            $table->string('completeness_state')->default('missing');
            $table->jsonb('summary')->default('{}');
            $table->timestampTz('published_at')->nullable();
            $table->timestampTz('archived_at')->nullable();
            $table->timestampTz('generated_at')->nullable();
            $table->timestamps();

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

        DB::statement("
            CREATE UNIQUE INDEX environment_reviews_fingerprint_mutable_unique
            ON environment_reviews (workspace_id, managed_environment_id, fingerprint)
            WHERE fingerprint IS NOT NULL AND status IN ('draft', 'ready', 'failed')
        ");
    }

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