'use strict';

module.exports = {
  up: async (queryInterface, Sequelize) => {
    // Add customer_po_id to sales_order table
    await queryInterface.addColumn('sales_order', 'customer_po_id', {
      type: Sequelize.INTEGER,
      allowNull: true,
      references: {
        model: 'customer_po',
        key: 'id'
      },
      onUpdate: 'CASCADE',
      onDelete: 'SET NULL',
      comment: 'Reference to Customer PO if created from Sales Order'
    });

    // Add sales_order_id to customer_po table
    await queryInterface.addColumn('customer_po', 'sales_order_id', {
      type: Sequelize.INTEGER,
      allowNull: true,
      references: {
        model: 'sales_order',
        key: 'id'
      },
      onUpdate: 'CASCADE',
      onDelete: 'SET NULL',
      comment: 'Reference to Sales Order if Customer PO was created from Sales Order'
    });

    // Add indexes for performance
    await queryInterface.addIndex('sales_order', ['customer_po_id'], {
      name: 'idx_sales_order_customer_po'
    });

    await queryInterface.addIndex('customer_po', ['sales_order_id'], {
      name: 'idx_customer_po_sales_order'
    });
  },

  down: async (queryInterface, Sequelize) => {
    await queryInterface.removeIndex('customer_po', 'idx_customer_po_sales_order');
    await queryInterface.removeIndex('sales_order', 'idx_sales_order_customer_po');
    await queryInterface.removeColumn('customer_po', 'sales_order_id');
    await queryInterface.removeColumn('sales_order', 'customer_po_id');
  }
};

