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

const CattleBatchAnimal = sequelize.define('CattleBatchAnimal', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true,
    allowNull: false
  },
  batchId: {
    type: DataTypes.INTEGER,
    allowNull: false,
    field: 'batch_id',
    comment: '批次ID'
  },
  animalId: {
    type: DataTypes.INTEGER,
    allowNull: false,
    field: 'animal_id',
    comment: '动物ID'
  },
  addedDate: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW,
    field: 'added_date',
    comment: '添加日期'
  },
  addedBy: {
    type: DataTypes.INTEGER,
    allowNull: true,
    field: 'added_by',
    comment: '添加人ID'
  }
}, {
  tableName: 'cattle_batch_animals',
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at',
  comment: '批次牛只关联表'
});

// 定义关联关系
CattleBatchAnimal.associate = (models) => {
  // 关联到批次
  CattleBatchAnimal.belongsTo(models.CattleBatch, {
    foreignKey: 'batchId',
    as: 'batch'
  });

  // 关联到牛只
  CattleBatchAnimal.belongsTo(models.IotCattle, {
    foreignKey: 'animalId',
    as: 'cattle'
  });

  // 关联到添加人
  CattleBatchAnimal.belongsTo(models.User, {
    foreignKey: 'addedBy',
    as: 'adder'
  });
};

module.exports = CattleBatchAnimal;
