<?php

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('review_packs', 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('status')->default('queued');
            $table->string('fingerprint', 64)->nullable();
            $table->string('previous_fingerprint', 64)->nullable();
            $table->jsonb('summary')->default('{}');
            $table->jsonb('options')->default('{}');
            $table->string('file_disk')->nullable();
            $table->string('file_path')->nullable();
            $table->bigInteger('file_size')->nullable();
            $table->string('sha256', 64)->nullable();
            $table->timestampTz('generated_at')->nullable();
            $table->timestampTz('expires_at')->nullable();
            $table->timestamps();

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

        DB::statement('
            CREATE UNIQUE INDEX review_packs_fingerprint_unique
            ON review_packs (workspace_id, managed_environment_id, fingerprint)
            WHERE fingerprint IS NOT NULL AND status NOT IN (\'expired\', \'failed\')
        ');
    }

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