const sequelize = require('../config/database');
const { DataTypes } = require('sequelize');

const Farmer = sequelize.define('Farmer', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  account: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true,
    comment: '账号'
  },
  org_code: {
    type: DataTypes.STRING,
    allowNull: true,
    comment: '机构识别码'
  },
  nickname: {
    type: DataTypes.STRING,
    allowNull: false,
    comment: '账号昵称'
  },
  real_name: {
    type: DataTypes.STRING,
    allowNull: false,
    comment: '真实姓名'
  },
  farm_name: {
    type: DataTypes.STRING,
    allowNull: false,
    comment: '养殖场名称'
  },
  farm_type: {
    type: DataTypes.STRING,
    allowNull: false,
    comment: '养殖场类型',
    validate: {
      isIn: [['规模', '散养', '其他']]
    }
  },
  animal_type: {
    type: DataTypes.STRING,
    allowNull: false,
    comment: '养殖场种类',
    validate: {
      isIn: [['牛', '羊', '猪', '鸡', '其他']]
    }
  },
  animal_count: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: 0,
    comment: '养殖数量'
  },
  address: {
    type: DataTypes.STRING,
    allowNull: false,
    comment: '养殖场地址'
  },
  register_time: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW,
    comment: '登记时间'
  },
  registrar: {
    type: DataTypes.STRING,
    allowNull: false,
    comment: '登记人'
  },
  update_time: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW,
    comment: '更新时间'
  },
  status: {
    type: DataTypes.ENUM('active', 'inactive', 'closed'),
    allowNull: false,
    defaultValue: 'active',
    comment: '状态：active-正常，inactive-暂停，closed-关闭'
  }
}, {
  tableName: 'farmers',
  timestamps: true,
  createdAt: 'register_time',
  updatedAt: 'update_time',
  paranoid: false,
  indexes: [
    {
      name: 'idx_farmer_account',
      fields: ['account']
    },
    {
      name: 'idx_farmer_farm_name',
      fields: ['farm_name']
    },
    {
      name: 'idx_farmer_status',
      fields: ['status']
    }
  ]
});

// 钩子函数，在保存前更新更新时间
Farmer.beforeSave((farmer) => {
  farmer.update_time = new Date();
});

module.exports = Farmer;