<?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('academy_events', function (Blueprint $table): void {
            $table->id();
            $table->string('event_type')->index();
            $table->string('content_type')->nullable()->index();
            $table->unsignedBigInteger('content_id')->nullable()->index();
            $table->foreignId('user_id')->nullable()->constrained()->nullOnDelete();
            $table->string('visitor_id', 120)->nullable()->index();
            $table->string('session_id', 120)->nullable()->index();
            $table->text('url')->nullable();
            $table->string('route_name')->nullable()->index();
            $table->text('referrer')->nullable();
            $table->string('utm_source')->nullable()->index();
            $table->string('utm_medium')->nullable()->index();
            $table->string('utm_campaign')->nullable()->index();
            $table->string('device_type')->nullable()->index();
            $table->string('browser')->nullable();
            $table->string('platform')->nullable();
            $table->string('country_code', 8)->nullable()->index();
            $table->boolean('is_logged_in')->default(false)->index();
            $table->boolean('is_subscriber')->default(false)->index();
            $table->boolean('is_admin')->default(false)->index();
            $table->boolean('is_bot')->default(false)->index();
            $table->boolean('is_crawler')->default(false)->index();
            $table->boolean('is_suspicious')->default(false)->index();
            $table->json('metadata')->nullable();
            $table->timestamp('occurred_at')->index();
            $table->timestamps();

            $table->index(['event_type', 'occurred_at']);
            $table->index(['content_type', 'content_id', 'occurred_at'], 'academy_events_content_occurred_idx');
            $table->index(['user_id', 'occurred_at']);
            $table->index(['visitor_id', 'occurred_at']);
            $table->index(['is_bot', 'is_admin', 'occurred_at'], 'academy_events_bot_admin_occurred_idx');
        });
    }

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