<?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('exam_questions', function (Blueprint $table) {
            $table->id();

            $table->foreignId('exam_attempt_id')
                ->constrained('exam_attempts')
                ->cascadeOnDelete();

            $table->foreignId('exam_id')
                ->constrained()
                ->cascadeOnDelete();

            $table->foreignId('question_id')
                ->nullable()
                ->constrained()
                ->nullOnDelete();

            $table->foreignId('course_id')
                ->nullable()
                ->constrained()
                ->nullOnDelete();

            $table->longText('question_text');
            $table->text('explanation')->nullable();

            /*
                Store options like:
                [
                    {"id": 1, "key": "A", "text": "Option A", "is_correct": false},
                    {"id": 2, "key": "B", "text": "Option B", "is_correct": true}
                ]
            */
            $table->json('options_snapshot')->nullable();

            $table->unsignedBigInteger('correct_option_id')->nullable();
            $table->string('correct_option_key', 5)->nullable();
            $table->longText('correct_option_text')->nullable();

            $table->unsignedBigInteger('selected_option_id')->nullable();
            $table->string('selected_option_key', 5)->nullable();
            $table->longText('selected_option_text')->nullable();

            $table->boolean('is_correct')->nullable();

            $table->unsignedInteger('sort_order')->default(0);

            $table->timestamps();

            $table->unique(['exam_attempt_id', 'question_id']);
            $table->index(['exam_attempt_id', 'is_correct']);
            $table->index(['exam_id', 'course_id']);
        });
    }

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