<?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('email_monitors', function (Blueprint $table) {
            $table->id();
            $table->string('name')->unique();
            $table->string('host');
            $table->json('ports')->comment('{ smtp:25, submission:587, imap:143, imaps:993, pop3:110, pop3s:995 }');

            $table->enum('status', ['online', 'warning', 'offline', 'unknown'])->default('unknown')->index();
            $table->json('port_status')->nullable()->comment('Per-port up/down + latency');
            $table->unsignedInteger('queue_size')->nullable();
            $table->unsignedInteger('queue_size_threshold')->default(1000);
            $table->json('blacklisted_on')->nullable()->comment('RBL list names that flag this host');
            $table->decimal('bounce_rate', 5, 2)->nullable()->comment('% over last 24h');
            $table->boolean('spf_valid')->nullable();
            $table->boolean('dkim_valid')->nullable();
            $table->boolean('dmarc_valid')->nullable();

            $table->timestamp('last_checked_at')->nullable()->index();
            $table->foreignId('server_id')->nullable()->constrained('servers')->nullOnDelete();
            $table->boolean('is_active')->default(true);
            $table->boolean('alerts_enabled')->default(true);
            $table->timestamps();
            $table->softDeletes();
        });

        Schema::create('ports', function (Blueprint $table) {
            $table->id();
            $table->foreignId('server_id')->constrained('servers')->cascadeOnDelete();
            $table->string('label')->nullable();
            $table->enum('protocol', ['tcp', 'udp', 'http', 'https'])->default('tcp');
            $table->unsignedSmallInteger('port');
            $table->string('service_type')->nullable()->comment('e.g. mysql, redis, ssh, smtp');
            $table->boolean('expect_banner')->default(false);
            $table->string('expected_banner_pattern')->nullable();

            $table->enum('status', ['up', 'down', 'timeout', 'unknown'])->default('unknown')->index();
            $table->unsignedInteger('last_latency_ms')->nullable();
            $table->string('last_banner', 512)->nullable();
            $table->timestamp('last_checked_at')->nullable()->index();

            $table->boolean('is_active')->default(true);
            $table->boolean('alerts_enabled')->default(true);
            $table->timestamps();

            $table->unique(['server_id', 'protocol', 'port'], 'uk_server_proto_port');
        });
    }

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