'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    // Add storage_location_id column to goods_receipt_note table (header/common location)
    await queryInterface.addColumn('goods_receipt_note', 'storage_location_id', {
      type: Sequelize.INTEGER,
      allowNull: true,
      references: {
        model: 'storage_location',
        key: 'id'
      },
      onUpdate: 'CASCADE',
      onDelete: 'SET NULL',
      comment: 'Common storage location for all items (can be overridden per item)'
    });

    // Add storage_location_id column to goods_receipt_note_item table (item-level location)
    await queryInterface.addColumn('goods_receipt_note_item', 'storage_location_id', {
      type: Sequelize.INTEGER,
      allowNull: true,
      references: {
        model: 'storage_location',
        key: 'id'
      },
      onUpdate: 'CASCADE',
      onDelete: 'SET NULL',
      comment: 'Storage location for this item (overrides header storage location if set)'
    });

    // Add indexes for better query performance
    await queryInterface.addIndex('goods_receipt_note', ['storage_location_id'], {
      name: 'idx_grn_storage_location_id'
    });

    await queryInterface.addIndex('goods_receipt_note_item', ['storage_location_id'], {
      name: 'idx_grn_item_storage_location_id'
    });
  },

  async down(queryInterface, Sequelize) {
    // Remove indexes first
    await queryInterface.removeIndex('goods_receipt_note_item', 'idx_grn_item_storage_location_id');
    await queryInterface.removeIndex('goods_receipt_note', 'idx_grn_storage_location_id');
    
    // Remove columns
    await queryInterface.removeColumn('goods_receipt_note_item', 'storage_location_id');
    await queryInterface.removeColumn('goods_receipt_note', 'storage_location_id');
  }
};
