'use strict';

module.exports = {
  up: async (queryInterface, Sequelize) => {
    // Add customer_po_id to delivery table
    await queryInterface.addColumn('delivery', '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 delivery is created from Customer PO'
    });

    // Add customer_po_id to sales_invoice table
    await queryInterface.addColumn('sales_invoice', '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 invoice is created from Customer PO'
    });

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

    await queryInterface.addIndex('sales_invoice', ['customer_po_id'], {
      name: 'idx_sales_invoice_customer_po'
    });
  },

  down: async (queryInterface, Sequelize) => {
    await queryInterface.removeIndex('sales_invoice', 'idx_sales_invoice_customer_po');
    await queryInterface.removeIndex('delivery', 'idx_delivery_customer_po');
    await queryInterface.removeColumn('sales_invoice', 'customer_po_id');
    await queryInterface.removeColumn('delivery', 'customer_po_id');
  }
};

