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 , organizationId, globalAccess) {
    try {
      if (!searchQuery) {
        throw new ValidationError('iam.errors.searchQueryRequired');
      }
      const tableColumns = {
        
          
          

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

          
            "organizations": [
              
                "name",
              
            ],
          
        
          
          

          
        
          
          

          
        
          
          

          
            "teams": [
              
                "team_name",
              
                "team_code",
              
                "description",
              
            ],
          
        
          
          

          
        
          
          

          
            "programs": [
              
                "program_name",
              
                "description",
              
            ],
          
        
          
          

          
            "learning_paths": [
              
                "path_name",
              
                "audience",
              
                "description",
              
            ],
          
        
          
          

          
            "missions": [
              
                "mission_title",
              
                "mission_code",
              
                "instructions",
              
                "video_url",
              
            ],
          
        
          
          

          
            "checklists": [
              
                "checklist_name",
              
                "description",
              
            ],
          
        
          
          

          
            "checklist_items": [
              
                "item_title",
              
                "instructions",
              
                "link_url",
              
            ],
          
        
          
          

          
        
          
          

          
        
          
          

          
            "quizzes": [
              
                "quiz_title",
              
            ],
          
        
          
          

          
            "quiz_questions": [
              
                "prompt",
              
            ],
          
        
          
          

          
            "quiz_choices": [
              
                "choice_text",
              
            ],
          
        
          
          

          
        
          
          

          
            "quiz_answers": [
              
                "answer_text",
              
            ],
          
        
          
          

          
            "simulations": [
              
                "simulation_title",
              
                "scenario_context",
              
                "success_criteria",
              
            ],
          
        
          
          

          
            "simulation_steps": [
              
                "step_text",
              
                "expected_response_hint",
              
            ],
          
        
          
          

          
            "content_assets": [
              
                "asset_title",
              
                "body",
              
                "asset_url",
              
            ],
          
        
          
          

          
            "ai_content_requests": [
              
                "prompt_text",
              
                "output_text",
              
            ],
          
        
          
          

          
            "knowledge_gap_assessments": [
              
                "insights_summary",
              
            ],
          
        
          
          

          
            "badges": [
              
                "badge_name",
              
                "badge_description",
              
            ],
          
        
          
          

          
            "user_badges": [
              
                "award_note",
              
            ],
          
        
          
          

          
            "point_ledger_entries": [
              
                "reason",
              
            ],
          
        
          
          

          
            "challenges": [
              
                "challenge_name",
              
                "description",
              
            ],
          
        
          
          

          
        
          
          

          
            "reward_catalog_items": [
              
                "item_name",
              
                "description",
              
            ],
          
        
          
          

          
            "reward_redemptions": [
              
                "fulfillment_note",
              
            ],
          
        
          
          

          
            "recognition_posts": [
              
                "message",
              
            ],
          
        
          
          

          
            "coaching_sessions": [
              
                "agenda",
              
                "notes",
              
                "action_items",
              
            ],
          
        
          
          

          
            "kpi_definitions": [
              
                "kpi_name",
              
                "kpi_key",
              
                "description",
              
            ],
          
        
          
          

          
            "kpi_measurements": [
              
                "notes",
              
            ],
          
        
          
          

          
            "qa_evaluations": [
              
                "interaction_reference",
              
                "summary_notes",
              
            ],
          
        
          
          

          
            "qa_scorecards": [
              
                "category_name",
              
                "comments",
              
            ],
          
        
          
          

          
            "surveys": [
              
                "survey_name",
              
                "introduction_text",
              
            ],
          
        
          
          

          
            "survey_questions": [
              
                "prompt",
              
            ],
          
        
          
          

          
            "survey_responses": [
              
                "overall_comment",
              
            ],
          
        
          
          

          
            "survey_response_items": [
              
                "answer_value",
              
            ],
          
        
          
          

          
            "reports": [
              
                "report_name",
              
                "filters_json",
              
            ],
          
        
          
          

          
            "audit_events": [
              
                "event_name",
              
                "entity_name",
              
                "entity_reference",
              
                "event_payload_json",
              
                "ip_address",
              
                "user_agent",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "missions": [
              
                "sequence_order",
              
                "estimated_minutes",
              
                "points_awarded",
              
                "coins_awarded",
              
            ],
          
        
          
          
          
        
          
          
          
            "checklist_items": [
              
                "sequence_order",
              
            ],
          
        
          
          
          
        
          
          
          
            "mission_attempts": [
              
                "score",
              
                "points_earned",
              
                "coins_earned",
              
            ],
          
        
          
          
          
            "quizzes": [
              
                "passing_score",
              
            ],
          
        
          
          
          
            "quiz_questions": [
              
                "sequence_order",
              
                "points",
              
            ],
          
        
          
          
          
            "quiz_choices": [
              
                "sequence_order",
              
            ],
          
        
          
          
          
            "quiz_submissions": [
              
                "score",
              
            ],
          
        
          
          
          
            "quiz_answers": [
              
                "points_earned",
              
            ],
          
        
          
          
          
        
          
          
          
            "simulation_steps": [
              
                "sequence_order",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "knowledge_gap_assessments": [
              
                "overall_score",
              
            ],
          
        
          
          
          
            "badges": [
              
                "threshold_value",
              
            ],
          
        
          
          
          
        
          
          
          
            "point_ledger_entries": [
              
                "points_delta",
              
                "coins_delta",
              
            ],
          
        
          
          
          
            "challenges": [
              
                "target_value",
              
                "reward_points",
              
                "reward_coins",
              
            ],
          
        
          
          
          
            "challenge_participants": [
              
                "current_value",
              
                "rank_position",
              
            ],
          
        
          
          
          
            "reward_catalog_items": [
              
                "cost_coins",
              
                "inventory_quantity",
              
            ],
          
        
          
          
          
            "reward_redemptions": [
              
                "quantity",
              
                "coins_spent",
              
            ],
          
        
          
          
          
            "recognition_posts": [
              
                "points_awarded",
              
                "coins_awarded",
              
            ],
          
        
          
          
          
        
          
          
          
            "kpi_definitions": [
              
                "target_value",
              
            ],
          
        
          
          
          
            "kpi_measurements": [
              
                "value",
              
            ],
          
        
          
          
          
            "qa_evaluations": [
              
                "overall_score",
              
            ],
          
        
          
          
          
            "qa_scorecards": [
              
                "category_score",
              
                "max_score",
              
            ],
          
        
          
          
          
        
          
          
          
            "survey_questions": [
              
                "sequence_order",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
      };

      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}%` }
                )
              )),
            ],
          };

           
          if (!globalAccess && tableName !== 'organizations' && organizationId) {
            whereCondition.organizationId = organizationId;
          }
          

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