'use strict';

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

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

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

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

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

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