'use strict';

module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.createTable('cattle_batches', {
      id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true,
        allowNull: false
      },
      name: {
        type: Sequelize.STRING(200),
        allowNull: false,
        comment: '批次名称'
      },
      code: {
        type: Sequelize.STRING(50),
        allowNull: false,
        unique: true,
        comment: '批次编号'
      },
      type: {
        type: Sequelize.ENUM('育成批次', '繁殖批次', '育肥批次', '隔离批次', '治疗批次'),
        allowNull: false,
        comment: '批次类型'
      },
      start_date: {
        type: Sequelize.DATE,
        allowNull: false,
        comment: '开始日期'
      },
      expected_end_date: {
        type: Sequelize.DATE,
        allowNull: true,
        comment: '预计结束日期'
      },
      actual_end_date: {
        type: Sequelize.DATE,
        allowNull: true,
        comment: '实际结束日期'
      },
      target_count: {
        type: Sequelize.INTEGER,
        allowNull: false,
        comment: '目标牛只数量'
      },
      current_count: {
        type: Sequelize.INTEGER,
        allowNull: false,
        defaultValue: 0,
        comment: '当前牛只数量'
      },
      manager: {
        type: Sequelize.STRING(100),
        allowNull: false,
        comment: '负责人'
      },
      status: {
        type: Sequelize.ENUM('进行中', '已完成', '已暂停'),
        allowNull: false,
        defaultValue: '进行中',
        comment: '状态'
      },
      remark: {
        type: Sequelize.TEXT,
        allowNull: true,
        comment: '备注'
      },
      farm_id: {
        type: Sequelize.INTEGER,
        allowNull: true,
        references: {
          model: 'farms',
          key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'SET NULL',
        comment: '所属农场ID'
      },
      created_at: {
        type: Sequelize.DATE,
        allowNull: false,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')
      },
      updated_at: {
        type: Sequelize.DATE,
        allowNull: false,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP')
      }
    }, {
      engine: 'InnoDB',
      charset: 'utf8mb4',
      collate: 'utf8mb4_unicode_ci',
      comment: '批次设置表'
    });

    // 添加索引
    await queryInterface.addIndex('cattle_batches', ['code'], {
      name: 'idx_cattle_batches_code',
      unique: true
    });

    await queryInterface.addIndex('cattle_batches', ['farm_id'], {
      name: 'idx_cattle_batches_farm_id'
    });

    await queryInterface.addIndex('cattle_batches', ['status'], {
      name: 'idx_cattle_batches_status'
    });

    await queryInterface.addIndex('cattle_batches', ['type'], {
      name: 'idx_cattle_batches_type'
    });
  },

  down: async (queryInterface, Sequelize) => {
    await queryInterface.dropTable('cattle_batches');
  }
};
