'use strict';

module.exports = {
  up: async (queryInterface, Sequelize) => {
    // Get current table structure
    const usersTable = await queryInterface.describeTable('Users');

    // Add pinHint column only if it doesn't exist
    if (!usersTable.pinHint) {
      await queryInterface.addColumn('Users', 'pinHint', {
        type: Sequelize.STRING(2),
        allowNull: true,
        comment: 'First and last digit of PIN for faster lookup'
      });
    }

    // Check if index exists before adding
    const indexes = await queryInterface.showIndex('Users');
    const indexExists = indexes.some(index => index.name === 'idx_users_pin_hint_active');

    if (!indexExists) {
      // Add index for faster PIN hint lookups
      await queryInterface.addIndex('Users', ['pinHint', 'isActive'], {
        name: 'idx_users_pin_hint_active'
      });
    }
  },

  down: async (queryInterface, Sequelize) => {
    // Check if index exists before removing
    const indexes = await queryInterface.showIndex('Users');
    const indexExists = indexes.some(index => index.name === 'idx_users_pin_hint_active');

    if (indexExists) {
      await queryInterface.removeIndex('Users', 'idx_users_pin_hint_active');
    }

    // Get current table structure
    const usersTable = await queryInterface.describeTable('Users');

    // Remove column only if it exists
    if (usersTable.pinHint) {
      await queryInterface.removeColumn('Users', 'pinHint');
    }
  }
};