'use strict';

module.exports = {
  up: async (queryInterface, Sequelize) => {
    // Add serial_number field to key transaction item tables
    const tables = [
      'gate_entry_item',
      'goods_receipt_note_item',
      'inventory_goods_receipt_item',
      'inventory_goods_issue_item',
      'material_issue_item',
      'material_return_note_item',
      'inventory_stock_transfer_item',
      'inventory_stock_adjustment_item',
      'delivery_item',
      'sales_invoice_item'
    ];

    for (const table of tables) {
      // Check if column already exists before adding
      const tableDescription = await queryInterface.describeTable(table);
      if (!tableDescription.serial_number) {
        await queryInterface.addColumn(table, 'serial_number', {
          type: Sequelize.STRING(100),
          allowNull: true,
          comment: 'Serial number for serial-managed materials'
        });
      }
    }

    // Add serial_numbers JSON field for multiple serials per item
    for (const table of tables) {
      const tableDescription = await queryInterface.describeTable(table);
      if (!tableDescription.serial_numbers) {
        await queryInterface.addColumn(table, 'serial_numbers', {
          type: Sequelize.TEXT,
          allowNull: true,
          comment: 'JSON array of serial numbers for items with multiple serials'
        });
      }
    }
  },

  down: async (queryInterface, Sequelize) => {
    const tables = [
      'gate_entry_item',
      'goods_receipt_note_item',
      'inventory_goods_receipt_item',
      'inventory_goods_issue_item',
      'material_issue_item',
      'material_return_note_item',
      'inventory_stock_transfer_item',
      'inventory_stock_adjustment_item',
      'delivery_item',
      'sales_invoice_item'
    ];

    for (const table of tables) {
      try {
        await queryInterface.removeColumn(table, 'serial_numbers');
      } catch (error) {
        // Column may not exist, ignore error
      }
      try {
        await queryInterface.removeColumn(table, 'serial_number');
      } catch (error) {
        // Column may not exist, ignore error
      }
    }
  }
};

