'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    // Add vendor_type_id as an alias to vendor_category_id
    // This allows backward compatibility and easier querying
    await queryInterface.addColumn('business_partner', 'vendor_type_id', {
      type: Sequelize.INTEGER,
      allowNull: true,
      references: {
        model: 'vendor_category',
        key: 'id'
      },
      onUpdate: 'CASCADE',
      onDelete: 'SET NULL',
      comment: 'Alias for vendor_category_id - used for filtering vendors by type/category'
    });

    // Copy data from vendor_category_id to vendor_type_id for existing records
    await queryInterface.sequelize.query(
      `UPDATE business_partner SET vendor_type_id = vendor_category_id WHERE vendor_category_id IS NOT NULL`
    );

    await queryInterface.addIndex('business_partner', {
      fields: ['vendor_type_id'],
      name: 'business_partner_vendor_type_id_idx'
    });
  },

  async down(queryInterface, Sequelize) {
    await queryInterface.removeIndex('business_partner', 'business_partner_vendor_type_id_idx');
    await queryInterface.removeColumn('business_partner', 'vendor_type_id');
  }
};

