const mongoose = require('mongoose');

const schoolDetailsSchema = new mongoose.Schema({
    userId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: [true, 'User ID is required'],
        unique: true
    },
    
    // Current Class Details
    currentClass: {
        type: String,
        required: [true, 'Current class is required'],
        enum: {
            values: ['6th', '7th', '8th', '9th', '10th'],
            message: 'Current class must be one of: 6th, 7th, 8th, 9th, 10th'
        }
    },
    
    // School Location Details
    
    schoolState: {
        type: String,
        required: [true, 'School state is required'],
        trim: true,
        maxlength: [50, 'State name cannot exceed 50 characters']
    },
    
    schoolDistrict: {
        type: String,
        required: [true, 'School district is required'],
        trim: true,
        maxlength: [50, 'District name cannot exceed 50 characters']
    },

    schoolVillage: {
        type: String,
        required: [true, 'School village is required'],
        trim: true,
        maxlength: [50, 'Village name cannot exceed 50 characters']
    },
    // School Details
    schoolName: {
        type: String,
        required: [true, 'School name is required'],
        trim: true,
        maxlength: [200, 'School name cannot exceed 200 characters']
    },
    
    boardType: {
        type: String,
        required: [true, 'Board type is required'],
        enum: {
            values: ['SSC/State Board', 'CBSE', 'ICSE', 'IB', 'Cambridge', 'Other'],
            message: 'Board type must be one of: SSC/State Board, CBSE, ICSE, IB, Cambridge, Other'
        }
    },
    
    boardTypeOther: {
        type: String,
        trim: true,
        maxlength: [100, 'Other board type cannot exceed 100 characters']
    },
    
    schoolType: {
        type: String,
        required: [true, 'School type is required'],
        enum: {
            values: ['Co-ed', 'Boys School', 'Girls School', 'Other'],
            message: 'School type must be one of: Co-ed, Boys School, Girls School, Other'
        }
    },
    
    schoolTypeOther: {
        type: String,
        trim: true,
        maxlength: [100, 'Other school type cannot exceed 100 characters']
    },
    
    yearOfJoiningSchool: {
        type: Number,
        required: [true, 'Year of joining school is required'],
        min: [1900, 'Year cannot be before 1900'],
        max: [new Date().getFullYear(), 'Year cannot be in the future']
    },
    
    // Optional Section Details
    section: {
        type: String,
        trim: true,
        maxlength: [50, 'Section cannot exceed 50 characters']
    },
    
  
    
    // Metadata
    isCompleted: {
        type: Boolean,
        default: false
    },
    
    lastUpdated: {
        type: Date,
        default: Date.now
    }
}, {
    timestamps: true
});

// Indexes for better performance
schoolDetailsSchema.index({ userId: 1 });
schoolDetailsSchema.index({ schoolName: 1 });
schoolDetailsSchema.index({ currentClass: 1 });

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

// Method to check if school details are complete
schoolDetailsSchema.methods.checkCompletion = function() {
    const requiredFields = [
        'currentClass', 'schoolState', 
        'schoolDistrict', 'schoolName', 'boardType', 
        'schoolType', 'yearOfJoiningSchool'
    ];
    
    const isComplete = requiredFields.every(field => {
        return this[field] && this[field].toString().trim().length > 0;
    });
    
    // If "Other" is selected for boardType, check boardTypeOther
    if (this.boardType === 'Other' && (!this.boardTypeOther || this.boardTypeOther.trim().length === 0)) {
        return false;
    }
    
    // If "Other" is selected for schoolType, check schoolTypeOther
    if (this.schoolType === 'Other' && (!this.schoolTypeOther || this.schoolTypeOther.trim().length === 0)) {
        return false;
    }
    
    this.isCompleted = isComplete;
    return isComplete;
};

// Static method to get completion percentage
schoolDetailsSchema.statics.getCompletionPercentage = function(schoolData) {
    const requiredFields = [
        'currentClass', 'schoolState', 
        'schoolDistrict', 'schoolName', 'boardType', 
        'schoolType', 'yearOfJoiningSchool'
    ];
    
    let completedFields = 0;
    
    requiredFields.forEach(field => {
        if (schoolData[field] && schoolData[field].toString().trim().length > 0) {
            completedFields++;
        }
    });
    
    // Check "Other" fields if applicable
    if (schoolData.boardType === 'Other' && schoolData.boardTypeOther && schoolData.boardTypeOther.trim().length > 0) {
        completedFields++;
    }
    
    if (schoolData.schoolType === 'Other' && schoolData.schoolTypeOther && schoolData.schoolTypeOther.trim().length > 0) {
        completedFields++;
    }
    
    // Calculate total possible fields
    let totalFields = requiredFields.length;
    if (schoolData.boardType === 'Other') totalFields++;
    if (schoolData.schoolType === 'Other') totalFields++;
    
    return Math.round((completedFields / totalFields) * 100);
};

// Virtual for formatted display
schoolDetailsSchema.virtual('displaySchool').get(function() {
    return `${this.schoolName} - ${this.currentClass}`;
});

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

module.exports = mongoose.model('SchoolDetails', schoolDetailsSchema);
