<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * Creates the self_paced_exam_attempts table — a single sitting of an Exam
     * by a Trainee. Stores the ordered question list, saved answers JSON,
     * timer boundaries, and submission status.
     */
    public function up(): void
    {
        Schema::create('self_paced_exam_attempts', function (Blueprint $table) {
            $table->id();

            $table->foreignId('enrollment_id')
                ->constrained('self_paced_enrollments')
                ->cascadeOnDelete();
            $table->foreignId('user_id')
                ->constrained('users')
                ->cascadeOnDelete();
            $table->foreignId('course_id')
                ->constrained('self_paced_courses')
                ->cascadeOnDelete();

            // Timer boundaries
            $table->timestamp('started_at')->nullable();
            $table->timestamp('submitted_at')->nullable();
            $table->timestamp('expires_at')->nullable();

            $table->enum('status', ['in_progress', 'submitted', 'timed_out', 'abandoned'])
                ->default('in_progress');

            // JSON stores {question_id: selected_option} e.g. {"5": "B", "12": "A"}
            $table->json('answers')->nullable();

            // Ordered list of question IDs selected for this attempt
            $table->json('question_ids')->nullable();

            $table->timestamps();

            $table->index('enrollment_id');
            $table->index('user_id');
            $table->index('course_id');
            $table->index('status');
        });
    }

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