'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    const table = 'routing_operation';
    const cols = await queryInterface.describeTable(table);

    if (!cols.operation_code) {
      await queryInterface.addColumn(table, 'operation_code', {
        type: Sequelize.STRING(50),
        allowNull: true,
        comment: 'Operation code (from Operation Name master)',
        after: 'operation_number',
      });
      await queryInterface.addIndex(table, ['operation_code'], { name: 'idx_routing_operation_operation_code' });
    }

    if (!cols.machine_id) {
      await queryInterface.addColumn(table, 'machine_id', {
        type: Sequelize.INTEGER,
        allowNull: true,
        references: { model: 'machine', key: 'id' },
        onUpdate: 'CASCADE',
        onDelete: 'SET NULL',
        comment: 'Machine (optional) for this routing operation',
        after: 'work_center_id',
      });
      await queryInterface.addIndex(table, ['machine_id'], { name: 'idx_routing_operation_machine_id' });
    }
  },

  async down(queryInterface) {
    const table = 'routing_operation';
    const cols = await queryInterface.describeTable(table);

    if (cols.machine_id) {
      try {
        await queryInterface.removeIndex(table, 'idx_routing_operation_machine_id');
      } catch (e) {
        // ignore
      }
      await queryInterface.removeColumn(table, 'machine_id');
    }

    if (cols.operation_code) {
      try {
        await queryInterface.removeIndex(table, 'idx_routing_operation_operation_code');
      } catch (e) {
        // ignore
      }
      await queryInterface.removeColumn(table, 'operation_code');
    }
  },
};

