// models/Lead.js
const mongoose = require('mongoose');

const leadSchema = new mongoose.Schema({
  companyId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Company',
    required: [true, 'Company ID is required']
  },
  leadNumber: {
    type: String,
    unique: true,
    sparse: true
  },
  customer: {
    name: {
      type: String,
      required: [true, 'Customer name is required'],
      trim: true
    },
    email: {
      type: String,
      required: [true, 'Customer email is required'],
      lowercase: true,
      trim: true,
      validate: {
        validator: function(v) {
          return /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/.test(v);
        },
        message: props => `${props.value} is not a valid email address!`
      }
    },
    phone: {
      type: String,
      trim: true
    },
    company: {
      type: String,
      trim: true
    }
  },
  priority: {
    type: String,
    enum: {
      values: ['low', 'medium', 'high'],
      message: '{VALUE} is not a valid priority'
    },
    default: 'medium'
  },
  status: {
    type: String,
    enum: {
      values: ['new', 'contacted', 'offer', 'won', 'lost'],
      message: '{VALUE} is not a valid status'
    },
    default: 'new'
  },
  assignedTo: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  },
  notes: {
    type: String,
    default: '',
    maxlength: [2000, 'Notes cannot exceed 2000 characters']
  },
  createdBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
  },
  updatedBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  }
}, {
  timestamps: true
});

// Generate lead number before saving
leadSchema.pre('save', async function(next) {
  if (!this.isNew || this.leadNumber) {
    return next();
  }
  
  try {
    const Company = mongoose.model('Company');
    const company = await Company.findById(this.companyId);
    
    if (!company) {
      const error = new Error('Company not found');
      error.statusCode = 404;
      return next(error);
    }
    
    const count = await this.constructor.countDocuments({ 
      companyId: this.companyId 
    });
    
    this.leadNumber = `LEAD-${company.code}-${String(count + 1).padStart(5, '0')}`;
    
    next();
  } catch (error) {
    next(error);
  }
});

// Indexes
leadSchema.index({ companyId: 1, status: 1 });
leadSchema.index({ companyId: 1, priority: 1 });
leadSchema.index({ 'customer.email': 1, companyId: 1 });
leadSchema.index({ createdAt: -1 });
leadSchema.index({ createdBy: 1 });
leadSchema.index({ assignedTo: 1 });

// Virtuals in JSON
leadSchema.set('toJSON', { virtuals: true });
leadSchema.set('toObject', { virtuals: true });

module.exports = mongoose.model('Lead', leadSchema);
