<?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('tenant_triage_reviews', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('workspace_id')->constrained('workspaces')->cascadeOnDelete();
            $table->foreignId('tenant_id')->constrained('tenants')->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', 'tenant_id'],
                'tenant_triage_reviews_lookup_index',
            );
            $table->index(
                ['tenant_id', 'concern_family', 'resolved_at'],
                'tenant_triage_reviews_tenant_family_index',
            );
        });

        DB::statement("
            CREATE UNIQUE INDEX tenant_triage_reviews_active_unique
            ON tenant_triage_reviews (workspace_id, tenant_id, concern_family)
            WHERE resolved_at IS NULL
        ");

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

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

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

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