const mongoose = require('mongoose');

const careerProgressSchema = 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'
        }
    },
    currentStage: {
        type: String,
        required: true,
        enum: ['class_6_10', 'class_11_12', 'graduation', 'working_professional']
    },
    goals: [{
        goalId: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'CareerGoal'
        },
        progress: {
            type: Number,
            min: 0,
            max: 100,
            default: 0
        },
        milestones: [{
            title: String,
            completed: {
                type: Boolean,
                default: false
            },
            completedAt: Date
        }]
    }],
    quizStats: {
        totalAttempts: {
            type: Number,
            default: 0
        },
        correctAnswers: {
            type: Number,
            default: 0
        },
        averageScore: {
            type: Number,
            default: 0
        },
        categoryScores: [{
            category: String,
            score: Number,
            attempts: Number
        }]
    },
    studyGroupActivity: {
        groupsJoined: {
            type: Number,
            default: 0
        },
        postsCreated: {
            type: Number,
            default: 0
        },
        helpfulAnswers: {
            type: Number,
            default: 0
        }
    },
    achievements: [{
        title: String,
        description: String,
        earnedAt: {
            type: Date,
            default: Date.now
        },
        type: {
            type: String,
            enum: ['quiz', 'study_group', 'goal_completion', 'streak', 'special']
        }
    }],
    streak: {
        current: {
            type: Number,
            default: 0
        },
        longest: {
            type: Number,
            default: 0
        },
        lastActiveDate: Date
    },
    lastUpdated: {
        type: Date,
        default: Date.now
    }
}, {
    timestamps: true
});

module.exports = mongoose.model('CareerProgress', careerProgressSchema);
