const mongoose = require('mongoose');

const personalDetailsSchema = new mongoose.Schema({
    userId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: [true, 'User ID is required'],
        unique: true
    },
    
    // Personal Information
    fullName: {
        type: String,
        required: [true, 'Full name is required'],
        trim: true,
        minlength: [2, 'Full name must be at least 2 characters'],
        maxlength: [100, 'Full name cannot exceed 100 characters']
    },
    
    gender: {
        type: String,
        required: [true, 'Gender is required'],
        enum: {
            values: ['Male', 'Female', 'Other'],
            message: 'Gender must be Male, Female, or Other'
        }
    },
    
    emailId: {
        type: String,
        required: [true, 'Email ID is required'],
        trim: true,
        lowercase: true,
        match: [
            /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
            'Please provide a valid email address'
        ]
    },
    
    bloodGroup: {
        type: String,
        required: [true, 'Blood group is required'],
        enum: {
            values: ['A+', 'A-', 'B+', 'B-', 'AB+', 'AB-', 'O+', 'O-'],
            message: 'Blood group must be one of the valid types'
        }
    },
    
    // Location Information
    pincodeNative: {
        type: String,
        required: [true, 'Native pincode is required'],
        match: [/^[1-9][0-9]{5}$/, 'Pincode must be a valid 6-digit number'],
        trim: true
    },
    
    state: {
        type: String,
        required: [true, 'State is required'],
        trim: true,
        maxlength: [50, 'State name cannot exceed 50 characters']
    },
    
    district: {
        type: String,
        required: [true, 'District is required'],
        trim: true,
        maxlength: [50, 'District name cannot exceed 50 characters']
    },
    
    nativePlace: {
        type: String,
        required: [true, 'Native place is required'],
        trim: true,
        maxlength: [100, 'Native place cannot exceed 100 characters']
    },
    
    
    // Additional Information
    nameMeaning: {
        type: String,
        trim: true,
        maxlength: [500, 'Name meaning cannot exceed 500 characters']
    },
    
    // Metadata
    isCompleted: {
        type: Boolean,
        default: false
    },
    
    lastUpdated: {
        type: Date,
        default: Date.now
    }
}, {
    timestamps: true
});

// Index for better query performance
personalDetailsSchema.index({ userId: 1 });
personalDetailsSchema.index({ pincodeNative: 1 });
personalDetailsSchema.index({ state: 1, district: 1 });

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

// Method to check if profile is complete
personalDetailsSchema.methods.checkCompletion = function() {
    const requiredFields = [
        'fullName', 'gender', 'emailId', 'bloodGroup',
        'pincodeNative', 'state', 'district', 'nativePlace'
    ];
    
    const isComplete = requiredFields.every(field => {
        return this[field] && this[field].toString().trim().length > 0;
    });
    
    this.isCompleted = isComplete;
    return isComplete;
};

// Static method to get profile completion percentage
personalDetailsSchema.statics.getCompletionPercentage = function(details) {
    const requiredFields = [
        'fullName', 'gender', 'emailId', 'bloodGroup',
        'pincodeNative', 'state', 'district', 'nativePlace'
    ];
    
    const optionalFields = ['nameMeaning'];
    const allFields = [...requiredFields, ...optionalFields];
    
    let completedFields = 0;
    
    allFields.forEach(field => {
        if (details[field] && details[field].toString().trim().length > 0) {
            completedFields++;
        }
    });
    
    return Math.round((completedFields / allFields.length) * 100);
};

// Virtual for formatted display
personalDetailsSchema.virtual('displayName').get(function() {
    return this.fullName || 'Not provided';
});

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

module.exports = mongoose.model('PersonalDetails', personalDetailsSchema);
