const mongoose = require('mongoose');

const jobEntrySchema = new mongoose.Schema({
    jobRole: {
        type: String,
        required: [true, 'Job role is required'],
        trim: true,
        maxlength: [100, 'Job role cannot exceed 100 characters']
    },
    
    companyName: {
        type: String,
        required: [true, 'Company name is required'],
        trim: true,
        maxlength: [200, 'Company name cannot exceed 200 characters']
    },
    
    industry: {
        type: String,
        required: [true, 'Industry is required'],
        enum: {
            values: ['IT', 'Government', 'Finance', 'Healthcare', 'Education', 'Manufacturing', 'Retail', 'Real Estate', 'Media', 'Consulting', 'Other'],
            message: 'Industry must be one of the predefined options'
        }
    },
    
    industryOther: {
        type: String,
        trim: true,
        maxlength: [100, 'Other industry cannot exceed 100 characters']
    },
    
    // Job Location Details
    jobPincode: {
        type: String,
        required: [true, 'Job pincode is required'],
        match: [/^[1-9][0-9]{5}$/, 'Pincode must be a valid 6-digit number'],
        trim: true
    },
    
    jobState: {
        type: String,
        required: [true, 'Job state is required'],
        trim: true,
        maxlength: [50, 'State name cannot exceed 50 characters']
    },
    
    jobDistrict: {
        type: String,
        required: [true, 'Job district is required'],
        trim: true,
        maxlength: [50, 'District name cannot exceed 50 characters']
    },
    
    jobCity: {
        type: String,
        required: [true, 'Job city is required'],
        trim: true,
        maxlength: [100, 'City name cannot exceed 100 characters']
    },
    
    jobLocality: {
        type: String,
        required: [true, 'Job locality is required'],
        trim: true,
        maxlength: [200, 'Locality cannot exceed 200 characters']
    },
    
    workplaceType: {
        type: String,
        enum: ['On-site', 'Remote', 'Hybrid'],
        default: 'On-site'
    },
    
    // Job Duration (Optional)
    startDate: {
        type: Date
    },
    
    endDate: {
        type: Date
    },
    
    isCurrentJob: {
        type: Boolean,
        default: false
    }
}, {
    timestamps: true
});

const workingProfessionalDetailsSchema = 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']
    },
    
    // Graduate Details (From GraduateDetails model)
    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']
    },
    
    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']
    },
    
    // Job Entries (Multiple entries allowed)
    jobEntries: [jobEntrySchema],
    
    // Metadata
    isCompleted: {
        type: Boolean,
        default: true
    },
    
    lastUpdated: {
        type: Date,
        default: Date.now
    }
}, {
    timestamps: true
});

// Indexes for better performance
workingProfessionalDetailsSchema.index({ userId: 1 });
workingProfessionalDetailsSchema.index({ schoolDetailsId: 1 });
workingProfessionalDetailsSchema.index({ collegePincode: 1 });
workingProfessionalDetailsSchema.index({ collegeName: 1 });
workingProfessionalDetailsSchema.index({ 'jobEntries.jobPincode': 1 });
workingProfessionalDetailsSchema.index({ 'jobEntries.companyName': 1 });

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

// Method to check if working professional details are complete
workingProfessionalDetailsSchema.methods.checkCompletion = function() {
    // Check school details reference
    const schoolComplete = this.schoolDetailsId && this.schoolDetailsId.toString().trim().length > 0;
    
    // Check graduate details
    const graduateRequiredFields = [
        'collegePincode', 'collegeState', 'collegeDistrict', 
        'collegeName', 'graduationJoiningYear', 'mainStream', 
        'branchStream', 'collegeType'
    ];
    
    const graduateComplete = graduateRequiredFields.every(field => {
        return this[field] && this[field].toString().trim().length > 0;
    });
    
    // Check "Other" fields for graduate 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;
        });
        if (!pgComplete) return false;
    }
    
    // Check job entries - at least one job entry is required
    if (!this.jobEntries || this.jobEntries.length === 0) {
        this.isCompleted = false;
        return false;
    }
    
    // Check if all job entries are complete
    const jobEntriesComplete = this.jobEntries.every(job => {
        const requiredFields = ['jobRole', 'companyName', 'industry', 'jobPincode', 'jobState', 'jobDistrict', 'jobCity', 'jobLocality'];
        
        const fieldsComplete = requiredFields.every(field => {
            return job[field] && job[field].toString().trim().length > 0;
        });
        
        // Check "Other" field if applicable
        if (job.industry === 'Other' && (!job.industryOther || job.industryOther.trim().length === 0)) {
            return false;
        }
        
        return fieldsComplete;
    });
    
    const isComplete = schoolComplete && graduateComplete && jobEntriesComplete;
    this.isCompleted = isComplete;
    return isComplete;
};

// Static method to get completion percentage
workingProfessionalDetailsSchema.statics.getCompletionPercentage = function(workingProfessionalData) {
    let totalFields = 0;
    let completedFields = 0;
    
    // School Details Reference
    totalFields++;
    if (workingProfessionalData.schoolDetailsId && workingProfessionalData.schoolDetailsId.toString().trim().length > 0) {
        completedFields++;
    }
    
    // Graduate Details
    const graduateRequiredFields = [
        'collegePincode', 'collegeState', 'collegeDistrict', 
        'collegeName', 'graduationJoiningYear', 'mainStream', 
        'branchStream', 'collegeType'
    ];
    
    graduateRequiredFields.forEach(field => {
        totalFields++;
        if (workingProfessionalData[field] && workingProfessionalData[field].toString().trim().length > 0) {
            completedFields++;
        }
    });
    
    // Add "Other" fields for graduate if applicable
    if (workingProfessionalData.mainStream === 'Other') {
        totalFields++;
        if (workingProfessionalData.mainStreamOther && workingProfessionalData.mainStreamOther.trim().length > 0) {
            completedFields++;
        }
    }
    
    if (workingProfessionalData.collegeType === 'Other') {
        totalFields++;
        if (workingProfessionalData.collegeTypeOther && workingProfessionalData.collegeTypeOther.trim().length > 0) {
            completedFields++;
        }
    }
    
    // Add PG fields if PG is pursuing/completed
    if (workingProfessionalData.isPursuingOrCompletedPG) {
        const pgFields = ['pgCollegeName', 'pgJoiningYear'];
        pgFields.forEach(field => {
            totalFields++;
            if (workingProfessionalData[field] && workingProfessionalData[field].toString().trim().length > 0) {
                completedFields++;
            }
        });
    }
    
    // Job Entries
    if (workingProfessionalData.jobEntries && workingProfessionalData.jobEntries.length > 0) {
        workingProfessionalData.jobEntries.forEach(job => {
            const requiredFields = ['jobRole', 'companyName', 'industry', 'jobPincode', 'jobState', 'jobDistrict', 'jobCity', 'jobLocality'];
            
            requiredFields.forEach(field => {
                totalFields++;
                if (job[field] && job[field].toString().trim().length > 0) {
                    completedFields++;
                }
            });
            
            // Add "Other" field if applicable
            if (job.industry === 'Other') {
                totalFields++;
                if (job.industryOther && job.industryOther.trim().length > 0) {
                    completedFields++;
                }
            }
        });
    } else {
        // If no job entries, add 8 fields as missing (minimum 1 job entry required)
        totalFields += 8;
    }
    
    return totalFields > 0 ? Math.round((completedFields / totalFields) * 100) : 0;
};

// Virtual for formatted display
workingProfessionalDetailsSchema.virtual('displayInfo').get(function() {
    if (!this.jobEntries || this.jobEntries.length === 0) {
        return 'No job entries';
    }
    
    const currentJob = this.jobEntries.find(job => job.isCurrentJob);
    if (currentJob) {
        return `${currentJob.jobRole} at ${currentJob.companyName}`;
    }
    
    return `${this.jobEntries[0].jobRole} at ${this.jobEntries[0].companyName}`;
});

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

module.exports = mongoose.model('WorkingProfessionalDetails', workingProfessionalDetailsSchema);
