<?php

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

return new class extends Migration
{
    protected $connection = 'sam_stat';

    public function up(): void
    {
        Schema::connection($this->connection)->create('stat_alerts', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('tenant_id');
            $table->string('domain', 50);
            $table->string('alert_type', 100)->comment('below_target, anomaly, threshold');
            $table->enum('severity', ['info', 'warning', 'critical'])->default('info');
            $table->string('title', 300);
            $table->text('message');
            $table->string('metric_code', 100)->nullable();
            $table->decimal('current_value', 18, 2)->nullable();
            $table->decimal('threshold_value', 18, 2)->nullable();
            $table->boolean('is_read')->default(false);
            $table->boolean('is_resolved')->default(false);
            $table->timestamp('resolved_at')->nullable();
            $table->unsignedBigInteger('resolved_by')->nullable();
            $table->timestamp('created_at')->nullable();

            $table->index(['tenant_id', 'is_read'], 'idx_tenant_unread');
            $table->index('severity', 'idx_severity');
            $table->index('domain', 'idx_domain');
        });
    }

    public function down(): void
    {
        Schema::connection($this->connection)->dropIfExists('stat_alerts');
    }
};