/**
 * 更新栏舍动物类型枚举值
 * 将中文枚举值改为英文枚举值
 */

module.exports = {
  up: async (queryInterface, Sequelize) => {
    const transaction = await queryInterface.sequelize.transaction();
    
    try {
      // 首先更新现有数据
      await queryInterface.sequelize.query(`
        UPDATE pens SET animal_type = 'horse' WHERE animal_type = '马';
      `, { transaction });
      
      await queryInterface.sequelize.query(`
        UPDATE pens SET animal_type = 'cattle' WHERE animal_type = '牛';
      `, { transaction });
      
      await queryInterface.sequelize.query(`
        UPDATE pens SET animal_type = 'sheep' WHERE animal_type = '羊';
      `, { transaction });
      
      await queryInterface.sequelize.query(`
        UPDATE pens SET animal_type = 'poultry' WHERE animal_type = '家禽';
      `, { transaction });
      
      await queryInterface.sequelize.query(`
        UPDATE pens SET animal_type = 'pig' WHERE animal_type = '猪';
      `, { transaction });
      
      // 修改枚举类型
      await queryInterface.changeColumn('pens', 'animal_type', {
        type: Sequelize.ENUM('horse', 'cattle', 'sheep', 'poultry', 'pig'),
        allowNull: false,
        comment: '动物类型'
      }, { transaction });
      
      await transaction.commit();
      console.log('栏舍动物类型枚举值更新成功');
    } catch (error) {
      await transaction.rollback();
      console.error('栏舍动物类型枚举值更新失败:', error);
      throw error;
    }
  },

  down: async (queryInterface, Sequelize) => {
    const transaction = await queryInterface.sequelize.transaction();
    
    try {
      // 恢复中文枚举值
      await queryInterface.sequelize.query(`
        UPDATE pens SET animal_type = '马' WHERE animal_type = 'horse';
      `, { transaction });
      
      await queryInterface.sequelize.query(`
        UPDATE pens SET animal_type = '牛' WHERE animal_type = 'cattle';
      `, { transaction });
      
      await queryInterface.sequelize.query(`
        UPDATE pens SET animal_type = '羊' WHERE animal_type = 'sheep';
      `, { transaction });
      
      await queryInterface.sequelize.query(`
        UPDATE pens SET animal_type = '家禽' WHERE animal_type = 'poultry';
      `, { transaction });
      
      await queryInterface.sequelize.query(`
        UPDATE pens SET animal_type = '猪' WHERE animal_type = 'pig';
      `, { transaction });
      
      // 恢复原始枚举类型
      await queryInterface.changeColumn('pens', 'animal_type', {
        type: Sequelize.ENUM('马', '牛', '羊', '家禽', '猪'),
        allowNull: false,
        comment: '动物类型'
      }, { transaction });
      
      await transaction.commit();
      console.log('栏舍动物类型枚举值回滚成功');
    } catch (error) {
      await transaction.rollback();
      console.error('栏舍动物类型枚举值回滚失败:', error);
      throw error;
    }
  }
};

