'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    // Add optional cross-company fields (backward compatible)
    await queryInterface.addColumn('inventory_stock_transfer', 'from_company_id', {
      type: Sequelize.INTEGER,
      allowNull: true,
      references: {
        model: 'company',
        key: 'id',
      },
      onUpdate: 'CASCADE',
      onDelete: 'SET NULL',
      comment: 'Optional: source company for cross-company transfers',
    });

    await queryInterface.addColumn('inventory_stock_transfer', 'to_company_id', {
      type: Sequelize.INTEGER,
      allowNull: true,
      references: {
        model: 'company',
        key: 'id',
      },
      onUpdate: 'CASCADE',
      onDelete: 'SET NULL',
      comment: 'Optional: destination company for cross-company transfers',
    });

    // Backfill existing rows to current company_id so legacy records remain consistent
    await queryInterface.sequelize.query(
      `
      UPDATE inventory_stock_transfer
      SET from_company_id = company_id, to_company_id = company_id
      WHERE from_company_id IS NULL OR to_company_id IS NULL
      `
    );

    await queryInterface.addIndex('inventory_stock_transfer', ['from_company_id']);
    await queryInterface.addIndex('inventory_stock_transfer', ['to_company_id']);
  },

  async down(queryInterface) {
    await queryInterface.removeIndex('inventory_stock_transfer', ['to_company_id']);
    await queryInterface.removeIndex('inventory_stock_transfer', ['from_company_id']);
    await queryInterface.removeColumn('inventory_stock_transfer', 'to_company_id');
    await queryInterface.removeColumn('inventory_stock_transfer', 'from_company_id');
  },
};


