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",
              
            ],
          
        
          
          
          
          

          
            "publishers": [
              
                "name",
              
                "country",
              
                "website_url",
              
                "description",
              
            ],
          
        
          
          

          
            "authors": [
              
                "name",
              
                "bio",
              
                "website_url",
              
            ],
          
        
          
          

          
            "genres": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "books": [
              
                "title",
              
                "subtitle",
              
                "isbn",
              
                "description",
              
            ],
          
        
          
          

          
        
          
          

          
            "bookmarks": [
              
                "label",
              
            ],
          
        
          
          

          
            "notes": [
              
                "title",
              
                "content",
              
            ],
          
        
          
          

          
            "camera_scan_sessions": [
              
                "fraud_reason",
              
            ],
          
        
          
          

          
            "coin_ledger_entries": [
              
                "description",
              
            ],
          
        
          
          

          
            "withdrawal_requests": [
              
                "payout_destination",
              
                "provider_reference",
              
                "admin_note",
              
            ],
          
        
          
          

          
            "payment_transactions": [
              
                "provider_transaction_reference",
              
                "failure_reason",
              
            ],
          
        
          
          

          
        
          
          

          
        
          
          

          
            "achievement_definitions": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
        
          
          

          
            "rank_tiers": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
        
          
          

          
            "challenge_definitions": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
        
          
          

          
            "quiz_definitions": [
              
                "title",
              
            ],
          
        
          
          

          
            "quiz_questions": [
              
                "prompt",
              
                "explanation",
              
            ],
          
        
          
          

          
            "quiz_answer_choices": [
              
                "choice_text",
              
            ],
          
        
          
          

          
        
          
          

          
        
          
          

          
            "book_clubs": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
        
          
          

          
            "club_chat_messages": [
              
                "message_text",
              
            ],
          
        
          
          

          
            "reading_circle_events": [
              
                "title",
              
                "agenda",
              
                "meeting_link",
              
            ],
          
        
          
          

          
            "recommendation_events": [
              
                "explanation",
              
            ],
          
        
          
          

          
            "push_notifications": [
              
                "title",
              
                "body",
              
                "deep_link",
              
            ],
          
        
          
          

          
            "fraud_flags": [
              
                "reason",
              
            ],
          
        
          
          

          
            "kyc_verifications": [
              
                "document_type",
              
                "full_name_on_document",
              
                "document_number",
              
                "review_note",
              
            ],
          
        
          
          

          
            "user_uploads": [
              
                "title",
              
                "rejection_reason",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "books": [
              
                "page_count",
              
                "word_count",
              
                "duration_seconds",
              
                "difficulty_score",
              
                "popularity_score",
              
            ],
          
        
          
          
          
            "user_library_items": [
              
                "progress_percent",
              
                "current_location",
              
            ],
          
        
          
          
          
            "bookmarks": [
              
                "location",
              
            ],
          
        
          
          
          
            "notes": [
              
                "location",
              
            ],
          
        
          
          
          
            "camera_scan_sessions": [
              
                "frames_analyzed",
              
                "pages_detected",
              
                "confidence_score",
              
                "coins_awarded",
              
            ],
          
        
          
          
          
            "coin_ledger_entries": [
              
                "amount_coins",
              
            ],
          
        
          
          
          
            "withdrawal_requests": [
              
                "coins_amount",
              
                "cash_amount_uzs",
              
            ],
          
        
          
          
          
            "payment_transactions": [
              
                "amount_uzs",
              
            ],
          
        
          
          
          
            "daily_login_rewards": [
              
                "coins_awarded",
              
                "streak_day",
              
            ],
          
        
          
          
          
            "reading_streaks": [
              
                "current_streak_days",
              
                "best_streak_days",
              
            ],
          
        
          
          
          
            "achievement_definitions": [
              
                "target_value",
              
            ],
          
        
          
          
          
            "user_achievements": [
              
                "progress_value",
              
            ],
          
        
          
          
          
            "rank_tiers": [
              
                "min_points",
              
                "max_points",
              
            ],
          
        
          
          
          
            "user_ranks": [
              
                "rank_points",
              
            ],
          
        
          
          
          
            "challenge_definitions": [
              
                "target_value",
              
                "reward_coins",
              
            ],
          
        
          
          
          
            "user_challenges": [
              
                "progress_value",
              
                "coins_awarded",
              
            ],
          
        
          
          
          
            "quiz_definitions": [
              
                "question_count",
              
                "time_limit_seconds",
              
            ],
          
        
          
          
          
            "quiz_questions": [
              
                "order_index",
              
            ],
          
        
          
          
          
            "quiz_answer_choices": [
              
                "order_index",
              
            ],
          
        
          
          
          
            "quiz_attempts": [
              
                "score_percent",
              
                "correct_count",
              
                "total_count",
              
                "coins_awarded",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "recommendation_events": [
              
                "score",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
      };

      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;
    }
  }
}