'use strict';

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

    // Allow multiple route cards per work order for rework cycles.
    try {
      await queryInterface.removeIndex(table, 'uniq_rc_work_order');
    } catch (e) {
      // ignore if index does not exist
    }

    try {
      await queryInterface.addIndex(table, ['work_order_id'], { name: 'idx_rc_work_order' });
    } catch (e) {
      // ignore if index already exists
    }

    if (!cols.previous_route_card_id) {
      await queryInterface.addColumn(table, 'previous_route_card_id', {
        type: Sequelize.INTEGER,
        allowNull: true,
        references: { model: 'route_card', key: 'id' },
        onUpdate: 'CASCADE',
        onDelete: 'SET NULL',
        after: 'work_order_id'
      });
    }

    try {
      await queryInterface.addIndex(table, ['previous_route_card_id'], { name: 'idx_rc_previous_route_card' });
    } catch (e) {
      // ignore if index already exists
    }
  },

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

    try {
      await queryInterface.removeIndex(table, 'idx_rc_previous_route_card');
    } catch (e) {
      // ignore if missing
    }

    if (cols.previous_route_card_id) {
      await queryInterface.removeColumn(table, 'previous_route_card_id');
    }

    try {
      await queryInterface.removeIndex(table, 'idx_rc_work_order');
    } catch (e) {
      // ignore if missing
    }

    try {
      await queryInterface.addIndex(table, ['work_order_id'], { unique: true, name: 'uniq_rc_work_order' });
    } catch (e) {
      // ignore if exists
    }
  }
};
