<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('ad_analytics_realtime', function (Blueprint $table) {
            $table->id();
            $table->foreignId('ad_id')->constrained()->onDelete('cascade');
            $table->enum('event_type', ['impression', 'view', 'click']);
            $table->timestamp('timestamp', 3)->comment('Millisecond precision timestamp'); // MySQL 5.7+
            $table->foreignId('user_id')->nullable()->constrained()->onDelete('set null');
            $table->string('session_id', 100)->nullable()->comment('Browser/app session');
            $table->enum('source', ['search', 'feed', 'related', 'direct'])->default('direct');
            $table->string('ip_address', 45)->nullable();
            $table->text('user_agent')->nullable();
            
            // Indexes for real-time queries
            $table->index(['ad_id', 'timestamp', 'event_type'], 'idx_realtime_lookup');
            $table->index('timestamp', 'idx_realtime_cleanup'); // For auto-purging
            $table->index('session_id');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('ad_analytics_realtime');
    }
};
