<?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_rules', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->boolean('is_global')->default(true);
            $table->foreignId('client_id')->nullable()->constrained('clients')->cascadeOnDelete();
            $table->boolean('enabled')->default(true);
            $table->json('statuses');
            $table->unsignedInteger('threshold_hours')->default(24);
            $table->unsignedInteger('check_every_minutes')->default(60);
            $table->json('recipients_roles')->nullable();
            $table->json('recipients_emails')->nullable();
            $table->boolean('cc_client')->default(false);
            $table->string('email_subject');
            $table->text('email_body');
            $table->unsignedInteger('renotify_every_hours')->nullable();
            $table->timestamp('last_run_at')->nullable();
            $table->timestamps();

            $table->index(['enabled', 'is_global']);
        });

        Schema::create('case_alerts', function (Blueprint $table) {
            $table->id();
            $table->foreignId('case_id')->constrained('cases')->cascadeOnDelete();
            $table->foreignId('alert_rule_id')->constrained('alert_rules')->cascadeOnDelete();
            $table->timestamp('notified_at');
            $table->timestamp('next_notify_at')->nullable();
            $table->unsignedInteger('notify_count')->default(1);
            $table->timestamps();

            $table->index(['case_id', 'notified_at']);
        });
    }

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