<?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
    {
        Schema::create('modsecurity_settings', function (Blueprint $table) {
            $table->id();
            $table->string('key')->unique();
            $table->text('value')->nullable();
            $table->timestamp('updated_at')->nullable();
        });

        // Seed default global config
        DB::table('modsecurity_settings')->insert([
            ['key' => 'engine_enabled',    'value' => '1',             'updated_at' => now()],
            ['key' => 'audit_log_enabled', 'value' => '1',             'updated_at' => now()],
            ['key' => 'active_ruleset',    'value' => 'OWASP-CRS-3.3', 'updated_at' => now()],
            ['key' => 'paranoia_level',    'value' => '1',             'updated_at' => now()],
        ]);

        Schema::create('modsecurity_rule_exclusions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('account_id')->nullable()->constrained('accounts')->cascadeOnDelete();
            $table->string('domain_name')->nullable();
            $table->string('rule_id');
            $table->text('reason')->nullable();
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();

            // MariaDB 64-char identifier limit — açık kısa isim ver
            $table->unique(['account_id', 'domain_name', 'rule_id'], 'modsec_excl_acc_dom_rule_unq');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('modsecurity_rule_exclusions');
        Schema::dropIfExists('modsecurity_settings');
    }
};
