const mongoose = require('mongoose');

const graduateDetailsSchema = new mongoose.Schema({
    userId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: [true, 'User ID is required'],
        unique: true
    },
    
    // Reference to SchoolDetailsWithoutCurrentClass
    schoolDetailsId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'SchoolDetailsWithoutCurrentClass',
        required: [true, 'School details ID is required']
    },
    
    // College Details
    collegePincode: {
        type: String,
        required: [true, 'College pincode is required'],
        match: [/^[1-9][0-9]{5}$/, 'Pincode must be a valid 6-digit number'],
        trim: true
    },
    
    collegeState: {
        type: String,
        required: [true, 'College state is required'],
        trim: true,
        maxlength: [50, 'State name cannot exceed 50 characters']
    },
    
    collegeDistrict: {
        type: String,
        required: [true, 'College district is required'],
        trim: true,
        maxlength: [50, 'District name cannot exceed 50 characters']
    },
    
    collegeName: {
        type: String,
        required: [true, 'College name is required'],
        trim: true,
        maxlength: [200, 'College name cannot exceed 200 characters']
    },
    
    graduationJoiningYear: {
        type: Number,
        required: [true, 'Graduation joining year is required'],
        min: [1900, 'Year cannot be before 1900'],
        max: [new Date().getFullYear(), 'Year cannot be in the future']
    },
    
    // Main Stream Details
    mainStream: {
        type: String,
        required: [true, 'Main stream is required'],
        enum: {
            values: ['BA', 'BCom', 'BTech', 'BSc', 'BBA', 'BCA', 'BPharm', 'BDS', 'MBBS', 'BArch', 'BFA', 'BHM', 'LLB', 'Other'],
            message: 'Main stream must be one of the predefined options'
        }
    },
    
    mainStreamOther: {
        type: String,
        trim: true,
        maxlength: [100, 'Other main stream cannot exceed 100 characters']
    },
    
    branchStream: {
        type: String,
        required: [true, 'Branch/Stream is required'],
        trim: true,
        maxlength: [100, 'Branch/Stream cannot exceed 100 characters']
    },
    
    collegeType: {
        type: String,
        required: [true, 'College type is required'],
        enum: {
            values: ['Co-ed', 'Boys College', 'Girls College', 'Other'],
            message: 'College type must be one of: Co-ed, Boys College, Girls College, Other'
        }
    },
    
    collegeTypeOther: {
        type: String,
        trim: true,
        maxlength: [100, 'Other college type cannot exceed 100 characters']
    },
    
    // PG Details (Optional)
    isPursuingOrCompletedPG: {
        type: Boolean,
        default: false
    },
    
    pgCollegeName: {
        type: String,
        trim: true,
        maxlength: [200, 'PG college name cannot exceed 200 characters']
    },
    
    pgJoiningYear: {
        type: Number,
        min: [1900, 'Year cannot be before 1900'],
        max: [new Date().getFullYear(), 'Year cannot be in the future']
    },
    
    // Metadata
    isCompleted: {
        type: Boolean,
        default: false
    },
    
    lastUpdated: {
        type: Date,
        default: Date.now
    }
}, {
    timestamps: true
});

// Indexes for better performance
graduateDetailsSchema.index({ userId: 1 });
graduateDetailsSchema.index({ schoolDetailsId: 1 });
graduateDetailsSchema.index({ collegePincode: 1 });
graduateDetailsSchema.index({ collegeName: 1 });

// Pre-save middleware to update lastUpdated timestamp
graduateDetailsSchema.pre('save', function(next) {
    this.lastUpdated = new Date();
    next();
});

// Method to check if graduate details are complete
graduateDetailsSchema.methods.checkCompletion = function() {
    const requiredFields = [
        // School Details Reference
        'schoolDetailsId',
        // College Details
        'collegePincode', 'collegeState', 'collegeDistrict', 
        'collegeName', 'graduationJoiningYear', 'mainStream', 
        'branchStream', 'collegeType'
    ];
    
    const isComplete = requiredFields.every(field => {
        return this[field] && this[field].toString().trim().length > 0;
    });
    
    // Check "Other" fields if applicable
    if (this.mainStream === 'Other' && (!this.mainStreamOther || this.mainStreamOther.trim().length === 0)) {
        return false;
    }
    
    if (this.collegeType === 'Other' && (!this.collegeTypeOther || this.collegeTypeOther.trim().length === 0)) {
        return false;
    }
    
    // If PG is marked as pursuing/completed, check PG fields
    if (this.isPursuingOrCompletedPG) {
        const pgFields = ['pgCollegeName', 'pgJoiningYear'];
        const pgComplete = pgFields.every(field => {
            return this[field] && this[field].toString().trim().length > 0;
        });
        this.isCompleted = isComplete && pgComplete;
    } else {
        this.isCompleted = isComplete;
    }
    
    return this.isCompleted;
};

// Static method to get completion percentage
graduateDetailsSchema.statics.getCompletionPercentage = function(graduateData) {
    const requiredFields = [
        // School Details Reference
        'schoolDetailsId',
        // College Details
        'collegePincode', 'collegeState', 'collegeDistrict', 
        'collegeName', 'graduationJoiningYear', 'mainStream', 
        'branchStream', 'collegeType'
    ];
    
    let allFields = [...requiredFields];
    
    // Add "Other" fields if applicable
    if (graduateData.mainStream === 'Other') {
        allFields.push('mainStreamOther');
    }
    
    if (graduateData.collegeType === 'Other') {
        allFields.push('collegeTypeOther');
    }
    
    // Add PG fields if PG is pursuing/completed
    if (graduateData.isPursuingOrCompletedPG) {
        const pgFields = ['pgCollegeName', 'pgJoiningYear'];
        allFields = [...allFields, ...pgFields];
    }
    
    let completedFields = 0;
    
    allFields.forEach(field => {
        if (graduateData[field] !== undefined && graduateData[field] !== null && 
            graduateData[field].toString().trim().length > 0) {
            completedFields++;
        }
    });
    
    return Math.round((completedFields / allFields.length) * 100);
};

// Virtual for formatted display
graduateDetailsSchema.virtual('displayCollege').get(function() {
    return `${this.collegeName} - ${this.branchStream}`;
});

// Ensure virtual fields are serialized
graduateDetailsSchema.set('toJSON', { virtuals: true });
graduateDetailsSchema.set('toObject', { virtuals: true });

module.exports = mongoose.model('GraduateDetails', graduateDetailsSchema);
