'use strict';

module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.createTable('cattle_pens', {
      id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true,
        allowNull: false
      },
      name: {
        type: Sequelize.STRING(100),
        allowNull: false,
        comment: '栏舍名称'
      },
      code: {
        type: Sequelize.STRING(50),
        allowNull: false,
        unique: true,
        comment: '栏舍编号'
      },
      type: {
        type: Sequelize.ENUM('育成栏', '产房', '配种栏', '隔离栏', '治疗栏'),
        allowNull: false,
        comment: '栏舍类型'
      },
      capacity: {
        type: Sequelize.INTEGER,
        allowNull: false,
        comment: '栏舍容量'
      },
      current_count: {
        type: Sequelize.INTEGER,
        allowNull: false,
        defaultValue: 0,
        comment: '当前牛只数量'
      },
      area: {
        type: Sequelize.DECIMAL(10, 2),
        allowNull: false,
        comment: '面积(平方米)'
      },
      location: {
        type: Sequelize.TEXT,
        allowNull: true,
        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_pens', ['code'], {
      name: 'idx_cattle_pens_code',
      unique: true
    });

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

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

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