<?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('moderator_permissions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->string('permission', 80);
            $table->foreignId('granted_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamp('created_at')->useCurrent();

            $table->unique(['user_id', 'permission']);
            $table->index('user_id');
        });

        // user_activity_logs — every significant action a logged-in user takes
        Schema::create('user_activity_logs', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->nullable()->constrained()->nullOnDelete();
            $table->string('session_id', 64)->nullable()->index();
            $table->string('action', 60);           // login, logout, comment, watchlist_add…
            $table->string('subject_type', 60)->nullable(); // Anime, Episode, Comment…
            $table->unsignedBigInteger('subject_id')->nullable();
            $table->string('ip', 45)->nullable()->index();
            $table->string('country', 80)->nullable()->index();
            $table->string('city', 80)->nullable();
            $table->string('device', 20)->nullable();
            $table->string('browser', 50)->nullable();
            $table->string('user_agent', 500)->nullable();
            $table->boolean('is_bot')->default(false)->index();
            $table->json('meta')->nullable();        // extra context
            $table->timestamp('created_at')->useCurrent()->index();

            $table->index(['user_id', 'created_at']);
            $table->index(['action', 'created_at']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('user_activity_logs');
        Schema::dropIfExists('moderator_permissions');
    }
};
