const mongoose = require('mongoose');

const parentSchema = new mongoose.Schema({
  parentId: {
    type: String,
    required: true,
    unique: true,
    trim: true
  },
  name: {
    type: String,
    required: true,
    trim: true
  },
  gender: {
    type: String,
    required: true,
    enum: ['Male', 'Female']
  },
  occupation: {
    type: String,
    required: true,
    trim: true
  },
  address: {
    type: String,
    required: true,
    trim: true
  },
  phone: {
    type: String,
    required: true,
    trim: true
  },
  email: {
    type: String,
    trim: true,
    lowercase: true
  },
  children: [{
    name: {
      type: String,
      trim: true
    },
    studentId: {
      type: String,
      trim: true
    },
    className: {
      type: String,
      trim: true
    },
    section: {
      type: String,
      trim: true
    }
  }],
  isActive: {
    type: Boolean,
    default: true
  }
}, {
  timestamps: true
});

// Index for better query performance
parentSchema.index({ parentId: 1 });
parentSchema.index({ email: 1 });
parentSchema.index({ phone: 1 });
parentSchema.index({ isActive: 1 });
parentSchema.index({ 'children.className': 1 });
parentSchema.index({ 'children.studentId': 1 });

// Static method to get all parents with pagination and search
parentSchema.statics.getAllParents = function(filters = {}, page = 1, limit = 10) {
  const { search = '', isActive = '', className = '', section = '' } = filters;
  
  const query = {};
  
  if (search) {
    query.$or = [
      { name: { $regex: search, $options: 'i' } },
      { parentId: { $regex: search, $options: 'i' } },
      { email: { $regex: search, $options: 'i' } },
      { phone: { $regex: search, $options: 'i' } },
      { 'children.name': { $regex: search, $options: 'i' } },
      { 'children.className': { $regex: search, $options: 'i' } },
      { 'children.studentId': { $regex: search, $options: 'i' } }
    ];
  }
  
  if (className) {
    query['children.className'] = { $regex: className, $options: 'i' };
  }
  
  if (section) {
    query['children.section'] = { $regex: section, $options: 'i' };
  }
  
  if (isActive === 'true' || isActive === 'false') {
    query.isActive = isActive === 'true';
  }

  return this.find(query)
    .sort({ createdAt: -1 })
    .limit(limit * 1)
    .skip((page - 1) * limit);
};

// Static method to get active parents only
parentSchema.statics.getActiveParents = function() {
  return this.find({ isActive: true }).sort({ name: 1 });
};

// Static method to get parents by class
parentSchema.statics.getParentsByClass = function(className, section = '') {
  const query = { 'children.className': className };
  if (section) {
    query['children.section'] = section;
  }
  return this.find(query).sort({ name: 1 });
};

// Instance method to get formatted data
parentSchema.methods.toJSON = function() {
  const parent = this.toObject();
  delete parent.__v;
  return parent;
};

module.exports = mongoose.model('Parent', parentSchema);