'use strict';

module.exports = {
  async up(queryInterface) {
    const table = 'route_card';
    const indexes = await queryInterface.showIndex(table);

    // Remove any unique index that is exactly on work_order_id.
    for (const idx of indexes) {
      const fields = (idx.fields || []).map((f) => f.attribute);
      if (idx.unique && fields.length === 1 && fields[0] === 'work_order_id') {
        try {
          await queryInterface.removeIndex(table, idx.name);
        } catch (e) {
          // ignore individual remove failures to keep migration idempotent
        }
      }
    }

    // Ensure a normal (non-unique) index exists.
    try {
      await queryInterface.addIndex(table, ['work_order_id'], { name: 'idx_rc_work_order' });
    } catch (e) {
      // ignore if it already exists
    }
  },

  async down(queryInterface) {
    const table = 'route_card';
    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
    }
  }
};
