<?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('websites', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('url');
            $table->enum('method', ['GET', 'HEAD', 'POST'])->default('GET');
            $table->string('expected_keyword')->nullable()->comment('Body must contain this string');
            $table->json('headers')->nullable();
            $table->unsignedSmallInteger('expected_status')->default(200);
            $table->unsignedSmallInteger('timeout_seconds')->default(10);
            $table->unsignedInteger('check_interval_seconds')->default(60);
            $table->boolean('follow_redirects')->default(true);
            $table->boolean('verify_ssl')->default(true);

            // Latest snapshot
            $table->enum('status', ['online', 'warning', 'offline', 'unknown'])->default('unknown')->index();
            $table->unsignedSmallInteger('last_status_code')->nullable();
            $table->unsignedInteger('last_response_time_ms')->nullable();
            $table->timestamp('last_checked_at')->nullable()->index();
            $table->decimal('uptime_30d', 6, 3)->nullable()->comment('Percentage');
            $table->unsignedSmallInteger('ssl_days_remaining')->nullable();
            $table->string('ssl_issuer')->nullable();

            $table->foreignId('server_id')->nullable()->constrained('servers')->nullOnDelete();
            $table->boolean('is_active')->default(true);
            $table->boolean('alerts_enabled')->default(true);
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();
            $table->softDeletes();

            $table->index(['is_active', 'last_checked_at']);
        });

        Schema::create('website_checks', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->foreignId('website_id')->constrained('websites')->cascadeOnDelete();
            $table->timestamp('checked_at')->index();
            $table->unsignedSmallInteger('status_code')->nullable();
            $table->unsignedInteger('response_time_ms')->nullable();
            $table->boolean('keyword_match')->nullable();
            $table->string('error_message', 512)->nullable();
            $table->string('agent_location')->nullable()->comment('Where the check was run from');

            $table->index(['website_id', 'checked_at'], 'idx_site_time');
        });
    }

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