<?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_attempt_answers', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('attempt_id');
            $table->unsignedBigInteger('question_id');
            $table->json('answer_data'); // Flexible JSON for different answer types
            $table->json('scoring_data')->nullable(); // Scoring details
            $table->decimal('score', 8, 2)->default(0);
            $table->decimal('max_score', 8, 2)->default(0);
            $table->boolean('is_correct')->default(false);
            $table->boolean('is_partial')->default(false);
            $table->json('feedback')->nullable(); // Automated feedback
            $table->text('manual_feedback')->nullable(); // Manual feedback
            $table->integer('time_spent')->default(0); // Time spent on this question
            $table->integer('attempts_count')->default(1); // Number of attempts for this question
            $table->timestamp('answered_at');
            $table->timestamps();

            // Indexes
            $table->index(['attempt_id', 'question_id']);
            $table->index(['question_id']);
            $table->index(['is_correct']);
            $table->index(['answered_at']);

            // Foreign keys
            $table->foreign('attempt_id')->references('id')->on('quiz_attempts')->onDelete('cascade');
            $table->foreign('question_id')->references('id')->on('quiz_questions')->onDelete('cascade');

            // Unique constraint to prevent duplicate answers
            $table->unique(['attempt_id', 'question_id']);
        });
    }

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