<?php

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

return new class extends Migration
{
    public function up(): void
    {
        // ── IP Whitelist — ModSecurity'den bypass edilecek IP/CIDR ────────────
        Schema::create('modsecurity_whitelist', function (Blueprint $table) {
            $table->id();
            $table->string('ip_or_cidr', 64);
            $table->string('domain_name', 253)->nullable()->comment('null = global');
            $table->string('label', 100)->nullable();
            $table->text('reason')->nullable();
            $table->boolean('is_active')->default(true);
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();

            $table->unique(['ip_or_cidr', 'domain_name']);
            $table->index('is_active');
        });

        // ── Custom rules — yöneticinin yazdığı raw SecRule satırları ─────────
        Schema::create('modsecurity_custom_rules', function (Blueprint $table) {
            $table->id();
            $table->string('name', 100);
            $table->text('description')->nullable();
            $table->longText('rule_content')->comment('Raw SecRule directive(s)');
            $table->string('category', 50)->default('custom');
            $table->boolean('is_enabled')->default(true);
            $table->string('domain_name', 253)->nullable();
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();
        });

        // ── Audit log events cache — sysapi modsec-audit-search bunu doldurur
        // Asıl kaynak /var/log/httpd/modsec_audit.log; bu tablo arama/filter için
        // index'lenmiş kopya.
        Schema::create('modsecurity_audit_events', function (Blueprint $table) {
            $table->id();
            $table->string('event_id', 64)->index()->comment('ModSec unique_id, dedupe için');
            $table->string('source_ip', 45)->index();
            $table->string('country_code', 2)->nullable();
            $table->string('domain_name', 253)->nullable()->index();
            $table->string('uri', 500);
            $table->string('method', 10)->default('GET');
            $table->string('rule_id', 12)->index();
            $table->string('rule_tag', 100)->nullable();
            $table->string('severity', 20)->nullable();
            $table->text('reason')->nullable();
            $table->string('action_taken', 20)->default('blocked')->comment('blocked|passed|warned');
            $table->integer('response_code')->nullable();
            $table->json('matched_data')->nullable();
            $table->timestamp('event_at')->useCurrent()->index();
            $table->timestamp('created_at')->useCurrent();

            $table->unique('event_id');
            $table->index(['event_at', 'rule_id']);
        });

        // ── CRS update history ────────────────────────────────────────────────
        Schema::create('modsecurity_crs_updates', function (Blueprint $table) {
            $table->id();
            $table->string('from_version', 20)->nullable();
            $table->string('to_version', 20);
            $table->string('status', 20)->default('pending');
            $table->text('changelog')->nullable();
            $table->text('error_message')->nullable();
            $table->foreignId('triggered_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();
        });

        // ── Additional global settings ─────────────────────────────────────────
        $now = now();
        DB::table('modsecurity_settings')->insert([
            ['key' => 'engine_mode',                'value' => 'on',     'updated_at' => $now],   // on, detection_only, off
            ['key' => 'request_body_access',        'value' => '1',      'updated_at' => $now],
            ['key' => 'response_body_access',       'value' => '0',      'updated_at' => $now],
            ['key' => 'request_body_limit',         'value' => '13107200', 'updated_at' => $now], // 12.5MB
            ['key' => 'request_body_nofiles_limit', 'value' => '131072',   'updated_at' => $now], // 128KB
            ['key' => 'audit_log_parts',            'value' => 'ABIJDEFHZ', 'updated_at' => $now],
            ['key' => 'default_action',             'value' => 'deny',     'updated_at' => $now], // deny, drop, block
            ['key' => 'anomaly_threshold_inbound',  'value' => '5',        'updated_at' => $now],
            ['key' => 'anomaly_threshold_outbound', 'value' => '4',        'updated_at' => $now],
            ['key' => 'crs_version',                'value' => '3.3.5',    'updated_at' => $now],
            ['key' => 'auto_exclude_wordpress',     'value' => '0',        'updated_at' => $now],
            ['key' => 'auto_exclude_drupal',        'value' => '0',        'updated_at' => $now],
            ['key' => 'auto_exclude_joomla',        'value' => '0',        'updated_at' => $now],
        ]);
    }

    public function down(): void
    {
        Schema::dropIfExists('modsecurity_crs_updates');
        Schema::dropIfExists('modsecurity_audit_events');
        Schema::dropIfExists('modsecurity_custom_rules');
        Schema::dropIfExists('modsecurity_whitelist');
    }
};
