<?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
    {
        if (!Schema::hasTable('exam_attempts')) {
            Schema::create('exam_attempts', function (Blueprint $table) {
                $table->id();
                $table->foreignId('exam_id')->constrained('exams')->onDelete('cascade');
                $table->foreignId('user_id')->constrained('users')->onDelete('cascade');
                $table->enum('status', ['in_progress', 'submitted', 'expired', 'abandoned'])->default('in_progress');
                $table->unsignedInteger('score')->nullable(); // Percentage score
                $table->boolean('passed')->nullable();
                $table->unsignedInteger('questions_answered')->default(0);
                $table->unsignedInteger('correct_answers')->nullable();
                $table->unsignedInteger('incorrect_answers')->nullable();
                $table->unsignedInteger('time_taken_seconds')->nullable();
                $table->timestamp('started_at')->nullable();
                $table->timestamp('submitted_at')->nullable();
                $table->timestamp('expires_at')->nullable();
                $table->unsignedInteger('attempt_number'); // Which attempt this is (1, 2, 3, etc.)
                $table->timestamps();
                
                $table->index(['exam_id', 'user_id']);
                $table->index(['user_id', 'status']);
                $table->index('expires_at');
            });
        }
    }

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