/**
 * 修复iot_cattle表外键约束问题
 * 
 * 问题描述：
 * - iot_cattle表的strain字段与cattle_user表的id字段类型不匹配
 * - 导致外键约束创建失败
 * 
 * 解决方案：
 * - 检查两个字段的类型并确保它们匹配
 * - 重新创建外键约束
 */

module.exports = {
  up: async (queryInterface, Sequelize) => {
    // 开始事务
    const transaction = await queryInterface.sequelize.transaction();
    
    try {
      // 1. 检查并修改cattle_user表的id字段类型为TINYINT以匹配iot_cattle表的strain字段
      await queryInterface.changeColumn('cattle_user', 'id', {
        type: Sequelize.TINYINT,
        allowNull: false,
        comment: '用途ID'
      }, { transaction });
      
      // 2. 删除现有的不兼容外键约束（如果存在）
      await queryInterface.sequelize.query(
        'ALTER TABLE iot_cattle DROP FOREIGN KEY IF EXISTS iot_cattle_ibfk_2',
        { transaction }
      );
      
      // 3. 确保iot_cattle表的strain字段类型为TINYINT
      await queryInterface.changeColumn('iot_cattle', 'strain', {
        type: Sequelize.TINYINT,
        allowNull: false,
        comment: '品系'
      }, { transaction });
      
      // 4. 重新创建外键约束
      await queryInterface.sequelize.query(
        'ALTER TABLE iot_cattle ADD CONSTRAINT iot_cattle_ibfk_2 FOREIGN KEY (strain) REFERENCES cattle_user (id) ON DELETE RESTRICT ON UPDATE CASCADE',
        { transaction }
      );
      
      // 提交事务
      await transaction.commit();
      console.log('✅ 成功修复iot_cattle表外键约束问题');
    } catch (error) {
      // 回滚事务
      await transaction.rollback();
      console.error('❌ 修复iot_cattle表外键约束失败:', error.message);
      throw error;
    }
  },

  down: async (queryInterface, Sequelize) => {
    // 回滚操作
    const transaction = await queryInterface.sequelize.transaction();
    
    try {
      // 1. 删除外键约束
      await queryInterface.sequelize.query(
        'ALTER TABLE iot_cattle DROP FOREIGN KEY IF EXISTS iot_cattle_ibfk_2',
        { transaction }
      );
      
      // 2. 恢复cattle_user表的id字段类型（可根据需要调整）
      await queryInterface.changeColumn('cattle_user', 'id', {
        type: Sequelize.INTEGER,
        allowNull: false,
        comment: '用途ID'
      }, { transaction });
      
      // 提交事务
      await transaction.commit();
      console.log('✅ 成功回滚外键约束修复');
    } catch (error) {
      // 回滚事务
      await transaction.rollback();
      console.error('❌ 回滚外键约束修复失败:', error.message);
      throw error;
    }
  }
};