'use strict';

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

    if (cols.parent_work_order_id) {
      try {
        await queryInterface.removeIndex(table, 'idx_work_order_parent_work_order_id');
      } catch (e) {
        // ignore missing index
      }
      await queryInterface.removeColumn(table, 'parent_work_order_id');
    }
  },

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

    if (!cols.parent_work_order_id) {
      await queryInterface.addColumn(table, 'parent_work_order_id', {
        type: Sequelize.INTEGER,
        allowNull: true,
        references: { model: 'work_order', key: 'id' },
        onUpdate: 'CASCADE',
        onDelete: 'SET NULL',
        after: 'routing_id',
        comment: 'Parent Work Order for rework cycle',
      });
      await queryInterface.addIndex(table, ['parent_work_order_id'], { name: 'idx_work_order_parent_work_order_id' });
    }
  },
};
