<?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('managed_environment_triage_reviews', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('workspace_id')->constrained('workspaces')->cascadeOnDelete();
            $table->foreignId('managed_environment_id')->constrained('managed_environments')->cascadeOnDelete();
            $table->string('concern_family', 64);
            $table->string('current_state', 64);
            $table->timestampTz('reviewed_at');
            $table->foreignId('reviewed_by_user_id')->nullable()->constrained('users')->nullOnDelete();
            $table->string('review_fingerprint', 64);
            $table->jsonb('review_snapshot')->default('{}');
            $table->timestampTz('last_seen_matching_at')->nullable();
            $table->timestampTz('resolved_at')->nullable();
            $table->timestamps();

            $table->index(
                ['workspace_id', 'concern_family', 'resolved_at', 'managed_environment_id'],
                'managed_environment_triage_reviews_lookup_index',
            );
            $table->index(
                ['managed_environment_id', 'concern_family', 'resolved_at'],
                'managed_environment_triage_reviews_environment_family_index',
            );
        });

        DB::statement("
            CREATE UNIQUE INDEX managed_environment_triage_reviews_active_unique
            ON managed_environment_triage_reviews (workspace_id, managed_environment_id, concern_family)
            WHERE resolved_at IS NULL
        ");

        if (DB::getDriverName() !== 'sqlite') {
            DB::statement("
                ALTER TABLE managed_environment_triage_reviews
                ADD CONSTRAINT managed_environment_triage_reviews_current_state_check
                CHECK (current_state IN ('reviewed', 'follow_up_needed'))
            ");
        }
    }

    public function down(): void
    {
        DB::statement('DROP INDEX IF EXISTS managed_environment_triage_reviews_active_unique');

        if (DB::getDriverName() !== 'sqlite') {
            DB::statement('ALTER TABLE managed_environment_triage_reviews DROP CONSTRAINT IF EXISTS managed_environment_triage_reviews_current_state_check');
        }

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