'use strict';

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

    if (!cols.routing_id) {
      await queryInterface.addColumn(table, 'routing_id', {
        type: Sequelize.INTEGER,
        allowNull: true,
        references: { model: 'routing', key: 'id' },
        onUpdate: 'CASCADE',
        onDelete: 'SET NULL',
        after: 'production_order_id',
        comment: 'Selected routing (from Routing master / Production Order)',
      });
      await queryInterface.addIndex(table, ['routing_id'], { name: 'idx_work_order_routing_id' });
    }
  },

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

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

