<?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::table('quiz_attempts', function (Blueprint $table) {
            // Put near other FKs; adjust "after" to a sensible column if you want
            $table->foreignId('exam_id')
                ->nullable()
                ->after('id')
                ->constrained('exams')
                ->cascadeOnDelete();

            // One attempt per user per exam (enforced only when exam_id is NOT NULL)
            $table->unique(['user_id','exam_id']);
        });
    }

    public function down(): void
    {
        Schema::table('quiz_attempts', function (Blueprint $table) {
            $table->dropUnique(['user_id','exam_id']);
            $table->dropConstrainedForeignId('exam_id'); // drops FK + column
        });
    }
};
