<?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('quiz_analytics', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('quiz_id')->nullable();
            $table->unsignedBigInteger('question_id')->nullable();
            $table->unsignedBigInteger('user_id')->nullable();
            $table->string('event_type'); // attempt_started, question_answered, attempt_completed, etc.
            $table->json('event_data'); // Event-specific data
            $table->json('metadata')->nullable(); // Additional metadata
            $table->string('session_id')->nullable();
            $table->ipAddress('ip_address')->nullable();
            $table->string('user_agent')->nullable();
            $table->timestamp('occurred_at');
            $table->timestamps();

            // Indexes
            $table->index(['quiz_id', 'event_type']);
            $table->index(['question_id', 'event_type']);
            $table->index(['user_id', 'event_type']);
            $table->index(['event_type']);
            $table->index(['occurred_at']);
            $table->index(['session_id']);

            // Foreign keys
            $table->foreign('quiz_id')->references('id')->on('quizzes')->onDelete('cascade');
            $table->foreign('question_id')->references('id')->on('quiz_questions')->onDelete('cascade');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });
    }

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