const db = require('../db/models');
const ValidationError = require('./notifications/errors/validation');

const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

/**
 * @param {string} permission
 * @param {object} currentUser
 */
async function checkPermissions(permission, currentUser) {

  if (!currentUser) {
    throw new ValidationError('auth.unauthorized');
  }

  const userPermission = currentUser.custom_permissions.find(
    (cp) => cp.name === permission,
  );

  if (userPermission) {
    return true;
  }

  try {
    if (!currentUser.app_role) {
      throw new ValidationError('auth.forbidden');
    }

    const permissions = await currentUser.app_role.getPermissions();

    return !!permissions.find((p) => p.name === permission);
  } catch (e) {
    throw e;
  }
}

module.exports = class SearchService {
  static async search(searchQuery, currentUser ) {
    try {
      if (!searchQuery) {
        throw new ValidationError('iam.errors.searchQueryRequired');
      }
      const tableColumns = {
        
          
          

          
            "users": [
              
                "firstName",
              
                "lastName",
              
                "phoneNumber",
              
                "email",
              
            ],
          
        
          
          
          
          

          
            "avatars": [
              
                "name",
              
                "model_key",
              
            ],
          
        
          
          

          
            "avatar_customizations": [
              
                "profile_name",
              
                "custom_color_hex",
              
                "pattern_custom_hex",
              
            ],
          
        
          
          

          
            "cosmetics": [
              
                "name",
              
                "asset_key",
              
            ],
          
        
          
          

          
            "boxes": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
        
          
          

          
        
          
          

          
        
          
          

          
            "titles": [
              
                "name",
              
                "tagline",
              
            ],
          
        
          
          

          
            "badges": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "achievements": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
        
          
          

          
            "quizzes": [
              
                "title",
              
                "description",
              
                "verified_badge_text",
              
            ],
          
        
          
          

          
            "quiz_questions": [
              
                "prompt",
              
            ],
          
        
          
          

          
            "question_answers": [
              
                "answer_text",
              
            ],
          
        
          
          

          
            "quiz_tags": [
              
                "name",
              
            ],
          
        
          
          

          
        
          
          

          
            "orbix_quiz_assistant_sessions": [
              
                "topic",
              
                "notes",
              
            ],
          
        
          
          

          
            "game_modes": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "matches": [
              
                "game_code",
              
            ],
          
        
          
          

          
            "match_players": [
              
                "display_name",
              
            ],
          
        
          
          

          
        
          
          

          
        
          
          

          
        
          
          

          
            "music_playlists": [
              
                "name",
              
            ],
          
        
          
          

          
            "music_tracks": [
              
                "name",
              
            ],
          
        
          
          

          
            "events": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "daily_rewards": [
              
                "name",
              
            ],
          
        
          
          

          
            "moderation_reports": [
              
                "reason",
              
            ],
          
        
          
          

          
            "community_modes": [
              
                "name",
              
                "description",
              
                "rules_summary",
              
            ],
          
        
          
          

          
            "community_mode_build_sessions": [
              
                "concept",
              
            ],
          
        
          
          

          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
            "avatars": [
              
                "drop_weight",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "boxes": [
              
                "price_yux",
              
            ],
          
        
          
          
          
            "box_items": [
              
                "drop_rate_percent",
              
            ],
          
        
          
          
          
            "purchases": [
              
                "amount_yux",
              
            ],
          
        
          
          
          
            "inventory_items": [
              
                "quantity",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "achievements": [
              
                "target_value",
              
                "reward_yux",
              
            ],
          
        
          
          
          
            "user_achievements": [
              
                "progress_value",
              
            ],
          
        
          
          
          
        
          
          
          
            "quiz_questions": [
              
                "time_limit_seconds",
              
                "points",
              
                "order_index",
              
            ],
          
        
          
          
          
            "question_answers": [
              
                "order_index",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "orbix_quiz_assistant_sessions": [
              
                "target_question_count",
              
            ],
          
        
          
          
          
        
          
          
          
            "matches": [
              
                "max_players",
              
                "question_count",
              
                "wheel_event_every_n_questions",
              
                "cat_interaction_every_n_questions",
              
                "starting_speed_kmh",
              
            ],
          
        
          
          
          
            "match_players": [
              
                "score_points",
              
                "correct_count",
              
                "incorrect_count",
              
                "yux_earned",
              
                "race_distance_km",
              
            ],
          
        
          
          
          
            "match_questions": [
              
                "question_index",
              
            ],
          
        
          
          
          
            "player_answers": [
              
                "points_awarded",
              
                "answer_time_ms",
              
            ],
          
        
          
          
          
            "wheel_events": [
              
                "trigger_question_index",
              
                "multiplier_value",
              
                "bonus_points",
              
                "bonus_yux",
              
            ],
          
        
          
          
          
        
          
          
          
            "music_tracks": [
              
                "duration_seconds",
              
                "order_index",
              
            ],
          
        
          
          
          
        
          
          
          
            "daily_rewards": [
              
                "day_index",
              
                "yux_amount",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "leaderboard_entries": [
              
                "rank_position",
              
                "score_value",
              
            ],
          
        
      };

      let allFoundRecords = [];

      for (const tableName in tableColumns) {
        if (tableColumns.hasOwnProperty(tableName)) {
          const attributesToSearch = tableColumns[tableName];
          const attributesIntToSearch = columnsInt[tableName] || [];
          const whereCondition = {
            [Op.or]: [
              ...attributesToSearch.map(attribute => ({
                [attribute]: {
                  [Op.iLike] : `%${searchQuery}%`,
                },
              })),
              ...attributesIntToSearch.map(attribute => (
                Sequelize.where(
                  Sequelize.cast(Sequelize.col(`${tableName}.${attribute}`), 'varchar'),
                  { [Op.iLike]: `%${searchQuery}%` }
                )
              )),
            ],
          };

          

          const hasPermission = await checkPermissions(`READ_${tableName.toUpperCase()}`, currentUser);
          if (!hasPermission) {
            continue;
          }

          const foundRecords = await db[tableName].findAll({
            where: whereCondition,
            attributes: [...tableColumns[tableName], 'id', ...attributesIntToSearch],
          });
      
          const modifiedRecords = foundRecords.map((record) => {
            const matchAttribute = [];
 
            for (const attribute of attributesToSearch) {
              if (record[attribute]?.toLowerCase()?.includes(searchQuery.toLowerCase())) {
                matchAttribute.push(attribute);
              }
            }

            for (const attribute of attributesIntToSearch) {
              const castedValue = String(record[attribute]);
              if (castedValue && castedValue.toLowerCase().includes(searchQuery.toLowerCase())) {
                matchAttribute.push(attribute);
              }
            }
      
            return {
              ...record.get(),
              matchAttribute,
              tableName,
            };
          });

          allFoundRecords = allFoundRecords.concat(modifiedRecords);
        }
      }

      return allFoundRecords;
    } catch (error) {
      throw error;
    }
  }
}