'use strict';

// Helper function to safely add an index if it doesn't exist
async function addIndexIfNotExists(queryInterface, tableName, fields, options) {
  try {
    const tableExists = await queryInterface.tableExists(tableName);
    if (!tableExists) {
      return;
    }

    const indexes = await queryInterface.showIndex(tableName);
    const indexName = options.name || `idx_${tableName}_${fields.join('_')}`;
    const indexExists = indexes.some(idx => idx.name === indexName);
    if (!indexExists) {
      await queryInterface.addIndex(tableName, fields, options);
    }
  } catch (error) {
    if (
      error.message &&
      (error.message.includes('already exists') ||
        error.message.includes('duplicate key value') ||
        (error.message.includes('relation') && error.message.includes('already exists')))
    ) {
      return;
    }
    throw error;
  }
}

module.exports = {
  async up(queryInterface, Sequelize) {
    // Add index on sessions.build_id for faster builds query
    await addIndexIfNotExists(queryInterface, 'sessions', ['build_id'], {
      name: 'idx_sessions_build_id',
    });

    // Add index on team_users.user_id for faster device filtering
    await addIndexIfNotExists(queryInterface, 'team_users', ['user_id'], {
      name: 'idx_team_users_user_id',
    });

    // Add index on team_devices.team_id for faster device filtering
    await addIndexIfNotExists(queryInterface, 'team_devices', ['team_id'], {
      name: 'idx_team_devices_team_id',
    });

    // Add index on nodes.created_at for faster ORDER BY
    await addIndexIfNotExists(queryInterface, 'nodes', ['created_at'], {
      name: 'idx_nodes_created_at',
    });
  },

  async down(queryInterface, Sequelize) {
    try {
      await queryInterface.removeIndex('sessions', 'idx_sessions_build_id');
    } catch (error) {
      // Ignore if index doesn't exist
    }
    try {
      await queryInterface.removeIndex('team_users', 'idx_team_users_user_id');
    } catch (error) {
      // Ignore if index doesn't exist
    }
    try {
      await queryInterface.removeIndex('team_devices', 'idx_team_devices_team_id');
    } catch (error) {
      // Ignore if index doesn't exist
    }
    try {
      await queryInterface.removeIndex('nodes', 'idx_nodes_created_at');
    } catch (error) {
      // Ignore if index doesn't exist
    }
  },
};
