const mongoose = require('mongoose');

const quizAttemptSchema = new mongoose.Schema({
    userId: {
        type: mongoose.Schema.Types.Mixed, // Accepts both ObjectId and String
        ref: 'User',
        required: true,
        validate: {
            validator: function(v) {
                // Allow ObjectId or string starting with 'demo_user_' or 'anonymous_'
                return mongoose.Types.ObjectId.isValid(v) || 
                       typeof v === 'string' && 
                       (v.startsWith('demo_user_') || v.startsWith('anonymous_'));
            },
            message: 'userId must be a valid ObjectId or demo/anonymous user string'
        }
    },
    quizId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Quiz',
        required: true
    },
    userAnswer: {
        type: Number,
        required: true,
        min: 0,
        max: 3
    },
    isCorrect: {
        type: Boolean,
        required: true
    },
    timeSpent: {
        type: Number, // in seconds
        default: 0
    },
    category: {
        type: String,
        required: true
    },
    difficulty: {
        type: String,
        required: true
    },
    stage: {
        type: String,
        required: true
    }
}, {
    timestamps: true
});

module.exports = mongoose.model('QuizAttempt', quizAttemptSchema);
