<?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_questions', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('quiz_id');
            $table->string('type'); // MULTIPLE_CHOICE, TRUE_FALSE, FILL_BLANK, MATCH, ORDER, MATRIX, FILE, DATE, CODE, etc.
            $table->text('question_text');
            $table->json('question_data'); // Flexible JSON for question-specific data
            $table->json('answer_data'); // Flexible JSON for answer data
            $table->json('scoring_data'); // Scoring configuration
            $table->json('validation_rules'); // Validation rules
            $table->json('metadata')->nullable(); // Additional metadata
            $table->json('i18n')->nullable(); // Internationalization data
            $table->integer('order')->default(0);
            $table->decimal('points', 8, 2)->default(1.0);
            $table->boolean('is_required')->default(true);
            $table->boolean('is_active')->default(true);
            $table->integer('version')->default(1);
            $table->unsignedBigInteger('parent_id')->nullable(); // For versioning
            $table->unsignedBigInteger('created_by');
            $table->unsignedBigInteger('updated_by')->nullable();
            $table->timestamps();
            $table->softDeletes();

            // Indexes
            $table->index(['quiz_id', 'order']);
            $table->index(['quiz_id', 'is_active']);
            $table->index(['type']);
            $table->index(['parent_id']);
            $table->index(['created_by']);

            // Foreign keys
            $table->foreign('quiz_id')->references('id')->on('quizzes')->onDelete('cascade');
            $table->foreign('created_by')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('updated_by')->references('id')->on('users')->onDelete('set null');
            $table->foreign('parent_id')->references('id')->on('quiz_questions')->onDelete('cascade');
        });
    }

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