const mongoose = require('mongoose');

const quizSubmissionSchema = 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'
        }
    },
    stage: {
        type: String,
        required: true,
        enum: ['class_6_10', 'class_11_12', 'graduation', 'working_professional']
    },
    category: {
        type: String,
        required: true,
        enum: ['gk', 'current_affairs', 'science', 'history', 'geography', 'economics', 'politics', 'sports', 'technology']
    },
    difficulty: {
        type: String,
        required: true,
        enum: ['easy', 'medium', 'hard']
    },
    totalQuestions: {
        type: Number,
        required: true
    },
    correctAnswers: {
        type: Number,
        required: true
    },
    score: {
        type: Number,
        required: true,
        min: 0,
        max: 100
    },
    totalTimeSpent: {
        type: Number,
        default: 0
    },
    submittedAt: {
        type: Date,
        default: Date.now
    }
}, {
    timestamps: true
});

// Index to prevent duplicate submissions
quizSubmissionSchema.index({ userId: 1, stage: 1, category: 1, difficulty: 1 }, { unique: true });

module.exports = mongoose.model('QuizSubmission', quizSubmissionSchema);
