<?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
    {
        // Analytics Events Table
        Schema::create('analytics_events', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->string('event_type', 50);
            $table->json('event_data')->nullable();
            $table->string('ip_address', 45)->nullable();
            $table->text('user_agent')->nullable();
            $table->timestamp('created_at');

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

        // User Sessions Table
        Schema::create('user_sessions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->timestamp('session_start');
            $table->timestamp('session_end')->nullable();
            $table->string('ip_address', 45)->nullable();
            $table->text('user_agent')->nullable();
            $table->integer('duration_seconds')->nullable();
            $table->integer('pages_visited')->default(0);
            $table->integer('actions_count')->default(0);
            $table->timestamps();

            $table->index(['user_id', 'session_start']);
            $table->index('session_start');
            $table->index(['session_end']);
        });

        // Add last_activity_at to users table if it doesn't exist
        if (!Schema::hasColumn('users', 'last_activity_at')) {
            Schema::table('users', function (Blueprint $table) {
                $table->timestamp('last_activity_at')->nullable()->after('updated_at');
                $table->index('last_activity_at');
            });
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('user_sessions');
        Schema::dropIfExists('analytics_events');
        
        if (Schema::hasColumn('users', 'last_activity_at')) {
            Schema::table('users', function (Blueprint $table) {
                $table->dropIndex(['last_activity_at']);
                $table->dropColumn('last_activity_at');
            });
        }
    }
};