<?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
    {
        if (!Schema::hasTable('forum_spam_keywords')) {
            Schema::create('forum_spam_keywords', function (Blueprint $table): void {
                $table->id();
                $table->string('keyword', 120)->unique();
                $table->timestamp('created_at')->useCurrent();
            });
        }

        if (!Schema::hasTable('forum_spam_domains')) {
            Schema::create('forum_spam_domains', function (Blueprint $table): void {
                $table->id();
                $table->string('domain', 191)->unique();
                $table->timestamp('created_at')->useCurrent();
            });
        }

        foreach ((array) config('forum.moderation.defaults.keywords', []) as $keyword) {
            $keyword = trim((string) $keyword);
            if ($keyword === '') {
                continue;
            }

            DB::table('forum_spam_keywords')->updateOrInsert(
                ['keyword' => $keyword],
                ['created_at' => now()]
            );
        }

        foreach ((array) config('forum.moderation.defaults.domains', []) as $domain) {
            $domain = strtolower(trim((string) $domain));
            if ($domain === '') {
                continue;
            }

            DB::table('forum_spam_domains')->updateOrInsert(
                ['domain' => $domain],
                ['created_at' => now()]
            );
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('forum_spam_domains');
        Schema::dropIfExists('forum_spam_keywords');
    }
};
