<?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('firewall_rules', function (Blueprint $table) {
            $table->id();
            $table->enum('type', ['allow_ip', 'deny_ip', 'allow_port', 'deny_port']);
            $table->string('value', 64)->comment('IP/CIDR (örn: 1.2.3.4/32) veya port numarası (örn: 8080)');
            $table->enum('protocol', ['tcp', 'udp', 'both'])->nullable();
            $table->string('comment')->nullable();
            $table->timestamp('expires_at')->nullable()->comment('null = kalıcı');
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();
            $table->index(['type', 'value']);
        });

        Schema::create('firewall_country_blocks', function (Blueprint $table) {
            $table->id();
            $table->string('country_code', 2)->unique()->comment('ISO 3166-1 alpha-2: CN, RU, vb.');
            $table->string('country_name');
            $table->boolean('is_active')->default(true);
            $table->timestamps();
        });

        Schema::create('cphulk_settings', function (Blueprint $table) {
            $table->id();
            $table->string('key')->unique();
            $table->text('value')->nullable();
            $table->timestamps();
        });

        // Seed default cPHulk settings
        $now = now();
        DB::table('cphulk_settings')->insert([
            ['key' => 'enabled',                              'value' => '1',   'created_at' => $now, 'updated_at' => $now],
            ['key' => 'max_failures_per_ip_per_hour',         'value' => '10',  'created_at' => $now, 'updated_at' => $now],
            ['key' => 'max_failures_per_account_per_hour',    'value' => '5',   'created_at' => $now, 'updated_at' => $now],
            ['key' => 'ip_block_duration_minutes',            'value' => '60',  'created_at' => $now, 'updated_at' => $now],
            ['key' => 'account_block_duration_minutes',       'value' => '15',  'created_at' => $now, 'updated_at' => $now],
            ['key' => 'notify_on_block',                      'value' => '1',   'created_at' => $now, 'updated_at' => $now],
            ['key' => 'alert_email',                          'value' => '',    'created_at' => $now, 'updated_at' => $now],
        ]);
    }

    public function down(): void
    {
        Schema::dropIfExists('cphulk_settings');
        Schema::dropIfExists('firewall_country_blocks');
        Schema::dropIfExists('firewall_rules');
    }
};
