/**
 * 为iot_cattle表添加外键约束
 */

module.exports = {
  up: async (queryInterface, Sequelize) => {
    // 添加外键约束
    await queryInterface.sequelize.query(`
      ALTER TABLE iot_cattle 
      ADD CONSTRAINT fk_iot_cattle_org_id 
      FOREIGN KEY (org_id) REFERENCES farms (id) 
      ON DELETE CASCADE ON UPDATE CASCADE
    `);
    
    await queryInterface.sequelize.query(`
      ALTER TABLE iot_cattle 
      ADD CONSTRAINT fk_iot_cattle_strain 
      FOREIGN KEY (strain) REFERENCES cattle_user (id) 
      ON DELETE RESTRICT ON UPDATE CASCADE
    `);
    
    await queryInterface.sequelize.query(`
      ALTER TABLE iot_cattle 
      ADD CONSTRAINT fk_iot_cattle_varieties 
      FOREIGN KEY (varieties) REFERENCES cattle_type (id) 
      ON DELETE RESTRICT ON UPDATE CASCADE
    `);
    
    await queryInterface.sequelize.query(`
      ALTER TABLE iot_cattle 
      ADD CONSTRAINT fk_iot_cattle_pen_id 
      FOREIGN KEY (pen_id) REFERENCES cattle_pens (id) 
      ON DELETE SET NULL ON UPDATE CASCADE
    `);
    
    await queryInterface.sequelize.query(`
      ALTER TABLE iot_cattle 
      ADD CONSTRAINT fk_iot_cattle_batch_id 
      FOREIGN KEY (batch_id) REFERENCES cattle_batches (id) 
      ON DELETE SET NULL ON UPDATE CASCADE
    `);
    
    console.log('✅ 成功为iot_cattle表添加外键约束');
  },

  down: async (queryInterface, Sequelize) => {
    // 删除外键约束
    await queryInterface.sequelize.query('ALTER TABLE iot_cattle DROP FOREIGN KEY IF EXISTS fk_iot_cattle_org_id');
    await queryInterface.sequelize.query('ALTER TABLE iot_cattle DROP FOREIGN KEY IF EXISTS fk_iot_cattle_strain');
    await queryInterface.sequelize.query('ALTER TABLE iot_cattle DROP FOREIGN KEY IF EXISTS fk_iot_cattle_varieties');
    await queryInterface.sequelize.query('ALTER TABLE iot_cattle DROP FOREIGN KEY IF EXISTS fk_iot_cattle_pen_id');
    await queryInterface.sequelize.query('ALTER TABLE iot_cattle DROP FOREIGN KEY IF EXISTS fk_iot_cattle_batch_id');
    
    console.log('✅ 成功删除iot_cattle表的外键约束');
  }
};