<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('alert_incidents', function (Blueprint $table) {
            $table->id();
            $table->foreignId('alert_rule_id')->constrained()->cascadeOnDelete();
            $table->foreignId('server_id')->constrained()->cascadeOnDelete();
            $table->string('state')->default('firing'); // firing|resolved
            $table->decimal('value', 8, 2)->default(0); // float-capable (see threshold, for `load`)
            // Set to "{rule_id}:{server_id}" ONLY while firing, NULL once resolved. The unique index
            // makes "at most one FIRING incident per rule+server" a DB invariant, so two concurrent
            // poll ticks cannot both open a duplicate incident (the loser hits a unique violation).
            $table->string('firing_key')->nullable()->unique();
            $table->timestamp('started_at')->nullable();
            $table->timestamp('resolved_at')->nullable();
            $table->timestamps();

            // Hot path: "is there an open incident for this rule+server?"
            $table->index(['alert_rule_id', 'server_id', 'state']);
        });
    }

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