const mongoose = require('mongoose');

const businessDetailsSchema = new mongoose.Schema({
    userId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: [true, 'User ID is required'],
        unique: true
    },
    
    // References to other models for better data organization
    schoolDetailsId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'SchoolDetailsWithoutCurrentClass',
        required: [true, 'School details reference is required']
    },
    
    graduateDetailsId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'GraduateDetails',
        required: [true, 'Graduate details reference is required']
    },
    
    // Business Details
    businessName: {
        type: String,
        required: [true, 'Business name is required'],
        trim: true,
        maxlength: [200, 'Business name cannot exceed 200 characters']
    },
    
    businessType: {
        type: String,
        required: [true, 'Business type is required'],
        enum: {
            values: ['Startup', 'MSME', 'Freelancer', 'Pvt Ltd'],
            message: 'Business type must be one of: Startup, MSME, Freelancer, Pvt Ltd'
        }
    },
    
    industry: {
        type: String,
        required: [true, 'Industry is required'],
        trim: true,
        maxlength: [100, 'Industry cannot exceed 100 characters']
    },
    
    yearsRunning: {
        type: String,
        required: [true, 'Years running is required'],
        enum: {
            values: ['0-1', '1-3', '3-5', '5+'],
            message: 'Years running must be one of: 0-1, 1-3, 3-5, 5+'
        }
    },
    
    // Business Location
    businessPincode: {
        type: String,
        required: [true, 'Business pincode is required'],
        match: [/^[1-9][0-9]{5}$/, 'Pincode must be a valid 6-digit number'],
        trim: true
    },
    
    businessState: {
        type: String,
        required: [true, 'Business state is required'],
        trim: true,
        maxlength: [50, 'State name cannot exceed 50 characters']
    },
    
    businessDistrict: {
        type: String,
        required: [true, 'Business district is required'],
        trim: true,
        maxlength: [50, 'District name cannot exceed 50 characters']
    },
    
    businessTown: {
        type: String,
        required: [true, 'Business town is required'],
        trim: true,
        maxlength: [100, 'Town name cannot exceed 100 characters']
    },
    
    websiteOrInstaLink: {
        type: String,
        trim: true,
        maxlength: [200, 'Website/Instagram link cannot exceed 200 characters']
    },
    
    // Business POC Details
    businessPOCName: {
        type: String,
        required: [true, 'Business POC name is required'],
        trim: true,
        maxlength: [100, 'POC name cannot exceed 100 characters']
    },
    
    businessPOCMobile: {
        type: String,
        required: [true, 'Business POC mobile is required'],
        match: [/^[6-9]\d{9}$/, 'Please enter a valid 10-digit mobile number'],
        trim: true
    },
    
    // Metadata
    isCompleted: {
        type: Boolean,
        default: true
    },
    
    lastUpdated: {
        type: Date,
        default: Date.now
    }
}, {
    timestamps: true
});

// Indexes for better performance
businessDetailsSchema.index({ userId: 1 });
businessDetailsSchema.index({ schoolDetailsId: 1 });
businessDetailsSchema.index({ graduateDetailsId: 1 });
businessDetailsSchema.index({ businessPincode: 1 });
businessDetailsSchema.index({ businessName: 1 });

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

// Method to check if business details are complete
businessDetailsSchema.methods.checkCompletion = function() {
    // Check if required references exist
    if (!this.schoolDetailsId || !this.graduateDetailsId) {
        this.isCompleted = false;
        return false;
    }
    
    // Check business details
    const businessRequiredFields = [
        'businessName', 'businessType', 'industry', 'yearsRunning',
        'businessPincode', 'businessState', 'businessDistrict', 
        'businessTown', 'businessPOCName', 'businessPOCMobile'
    ];
    
    const businessComplete = businessRequiredFields.every(field => {
        return this[field] && this[field].toString().trim().length > 0;
    });
    
    this.isCompleted = businessComplete;
    return businessComplete;
};

// Static method to get completion percentage
businessDetailsSchema.statics.getCompletionPercentage = function(businessData) {
    let totalFields = 0;
    let completedFields = 0;
    
    // Check if required references exist (2 fields)
    totalFields += 2;
    if (businessData.schoolDetailsId) completedFields++;
    if (businessData.graduateDetailsId) completedFields++;
    
    // Business Details
    const businessRequiredFields = [
        'businessName', 'businessType', 'industry', 'yearsRunning',
        'businessPincode', 'businessState', 'businessDistrict', 
        'businessTown', 'businessPOCName', 'businessPOCMobile'
    ];
    
    businessRequiredFields.forEach(field => {
        totalFields++;
        if (businessData[field] && businessData[field].toString().trim().length > 0) {
            completedFields++;
        }
    });
    
    return totalFields > 0 ? Math.round((completedFields / totalFields) * 100) : 0;
};

// Virtual for formatted display
businessDetailsSchema.virtual('displayBusiness').get(function() {
    return `${this.businessName} - ${this.businessType}`;
});

// Virtual to get populated school details
businessDetailsSchema.virtual('schoolDetails', {
    ref: 'SchoolDetailsWithoutCurrentClass',
    localField: 'schoolDetailsId',
    foreignField: '_id',
    justOne: true
});

// Virtual to get populated graduate details
businessDetailsSchema.virtual('graduateDetails', {
    ref: 'GraduateDetails',
    localField: 'graduateDetailsId',
    foreignField: '_id',
    justOne: true
});

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

module.exports = mongoose.model('BusinessDetails', businessDetailsSchema);
