const { Model, DataTypes } = require('sequelize');
const sequelize = require('../config/database');
const { leadSchema } = require('../validation/leadSchema');

class Lead extends Model {
  static async validateLead(leadData) {
    return await leadSchema.validateAsync(leadData);
  }
}

Lead.init({
  id: {
    type: DataTypes.UUID,
    defaultValue: DataTypes.UUIDV4,
    primaryKey: true
  },
  firstName: {
    type: DataTypes.STRING,
    allowNull: false,
    validate: {
      notEmpty: true,
      len: [2, 50]
    }
  },
  lastName: {
    type: DataTypes.STRING,
    allowNull: false,
    validate: {
      notEmpty: true,
      len: [2, 50]
    }
  },
  email: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true,
    validate: {
      isEmail: true
    }
  },
  phone: {
    type: DataTypes.STRING,
    validate: {
      is: /^\+?[1-9]\d{1,14}$/
    }
  },
  status: {
    type: DataTypes.ENUM('new', 'contacted', 'qualified', 'lost'),
    defaultValue: 'new',
    validate: {
      isIn: [['new', 'contacted', 'qualified', 'lost']]
    }
  },
  notes: {
    type: DataTypes.TEXT
  }
}, {
  sequelize,
  modelName: 'Lead',
  timestamps: true,
  indexes: [
    { fields: ['email'] },
    { fields: ['status'] }
  ]
});

module.exports = Lead;