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

          
        
          
          

          
            "user_lifestyle_baselines": [
              
                "typical_bedtime",
              
                "typical_wake_time",
              
                "recreational_substance_use",
              
                "exercise_types",
              
                "diet_pattern_other",
              
            ],
          
        
          
          

          
            "goals": [
              
                "follow_up_answer",
              
            ],
          
        
          
          

          
            "conditions": [
              
                "condition_name",
              
                "diagnosing_doctor",
              
                "management_plan",
              
                "notes",
              
            ],
          
        
          
          

          
            "surgeries": [
              
                "surgery_name",
              
                "notes",
              
            ],
          
        
          
          

          
            "implants_devices": [
              
                "device_name",
              
                "notes",
              
            ],
          
        
          
          

          
            "allergies": [
              
                "allergen",
              
                "reaction_notes",
              
            ],
          
        
          
          

          
            "family_histories": [
              
                "condition_name",
              
                "notes",
              
            ],
          
        
          
          

          
            "healthcare_providers": [
              
                "provider_name",
              
                "clinic_name",
              
                "phone",
              
                "email",
              
                "address",
              
                "notes",
              
            ],
          
        
          
          

          
            "pharmacies": [
              
                "pharmacy_name",
              
                "phone",
              
                "address",
              
                "notes",
              
            ],
          
        
          
          

          
            "medications": [
              
                "medication_name",
              
                "frequency_notes",
              
                "condition_treated",
              
                "instructions",
              
                "notes",
              
            ],
          
        
          
          

          
            "medication_doses": [
              
                "notes",
              
            ],
          
        
          
          

          
            "medication_side_effects": [
              
                "side_effect_name",
              
                "notes",
              
            ],
          
        
          
          

          
            "supplements": [
              
                "supplement_name",
              
                "dose_unit",
              
                "timing",
              
                "brand",
              
                "reason",
              
            ],
          
        
          
          

          
            "supplement_evidence_items": [
              
                "supplement_name",
              
                "summary",
              
                "mechanism",
              
                "benefits",
              
                "dosing_range",
              
                "timing_recommendations",
              
                "interactions",
              
                "side_effects",
              
                "avoid_who",
              
            ],
          
        
          
          

          
            "workouts": [
              
                "workout_name",
              
                "description",
              
                "warmup_notes",
              
                "cooldown_notes",
              
                "safety_notes",
              
                "video_url",
              
            ],
          
        
          
          

          
            "exercises": [
              
                "exercise_name",
              
                "instructions",
              
                "common_mistakes",
              
                "coaching_cues",
              
            ],
          
        
          
          

          
            "workout_exercises": [
              
                "beginner_modifications",
              
                "advanced_progressions",
              
            ],
          
        
          
          

          
            "workout_schedules": [
              
                "notes",
              
            ],
          
        
          
          

          
            "training_blocks": [
              
                "block_name",
              
                "notes",
              
            ],
          
        
          
          

          
            "workout_sessions": [
              
                "notes",
              
            ],
          
        
          
          

          
            "strength_sets": [
              
                "notes",
              
            ],
          
        
          
          

          
            "cardio_sessions": [
              
                "route_notes",
              
            ],
          
        
          
          

          
            "recovery_logs": [
              
                "notes",
              
            ],
          
        
          
          

          
            "heat_cold_exposures": [
              
                "notes",
              
            ],
          
        
          
          

          
            "flexibility_assessments": [
              
                "notes",
              
            ],
          
        
          
          

          
            "foods": [
              
                "food_name",
              
                "brand",
              
                "barcode",
              
                "micronutrients_json",
              
            ],
          
        
          
          

          
            "recipes": [
              
                "recipe_name",
              
                "tags_csv",
              
                "ingredients_text",
              
                "instructions_text",
              
                "nutrition_per_serving_json",
              
                "source_url",
              
            ],
          
        
          
          

          
            "recipe_collections": [
              
                "collection_name",
              
                "description",
              
            ],
          
        
          
          

          
            "meals": [
              
                "meal_title",
              
                "notes",
              
            ],
          
        
          
          

          
            "meal_items": [
              
                "quantity_unit",
              
            ],
          
        
          
          

          
            "nutrition_targets": [
              
                "macro_preset_name",
              
            ],
          
        
          
          

          
            "meal_plans": [
              
                "dietary_restrictions",
              
                "cuisine_preferences",
              
                "ai_plan_json",
              
            ],
          
        
          
          

          
            "meal_plan_items": [
              
                "notes",
              
            ],
          
        
          
          

          
            "grocery_lists": [
              
                "title",
              
                "notes",
              
            ],
          
        
          
          

          
            "grocery_items": [
              
                "item_name",
              
                "category",
              
                "unit",
              
            ],
          
        
          
          

          
            "hydration_logs": [
              
                "container_label",
              
            ],
          
        
          
          

          
            "fasting_sessions": [
              
                "notes",
              
            ],
          
        
          
          

          
            "ketone_glucose_logs": [
              
                "notes",
              
            ],
          
        
          
          

          
            "bowel_movements": [
              
                "associated_symptoms",
              
                "notes",
              
            ],
          
        
          
          

          
            "gut_symptom_logs": [
              
                "notes",
              
            ],
          
        
          
          

          
            "health_metrics": [
              
                "unit",
              
                "panel_json",
              
                "device_used",
              
                "notes",
              
            ],
          
        
          
          

          
            "symptom_logs": [
              
                "symptom_name",
              
                "triggers",
              
                "notes",
              
            ],
          
        
          
          

          
            "medical_appointments": [
              
                "clinic_location",
              
                "notes_to_discuss",
              
                "documents_to_bring",
              
                "post_appointment_notes",
              
                "follow_up_instructions",
              
            ],
          
        
          
          

          
            "lab_documents": [
              
                "title",
              
                "notes",
              
            ],
          
        
          
          

          
            "vaccinations": [
              
                "vaccine_name",
              
                "batch_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "ai_chat_threads": [
              
                "thread_title",
              
            ],
          
        
          
          

          
            "ai_chat_messages": [
              
                "content",
              
            ],
          
        
          
          

          
            "ai_generations": [
              
                "prompt_context_json",
              
                "result_json",
              
                "status_message",
              
            ],
          
        
          
          

          
            "habits": [
              
                "habit_name",
              
                "icon_name",
              
                "specific_days_csv",
              
                "motivation",
              
                "stacking_note",
              
            ],
          
        
          
          

          
            "habit_logs": [
              
                "notes",
              
            ],
          
        
          
          

          
            "habit_challenges": [
              
                "challenge_name",
              
                "description",
              
            ],
          
        
          
          

          
            "library_articles": [
              
                "title",
              
                "tags_csv",
              
                "content",
              
            ],
          
        
          
          

          
            "saved_articles": [
              
                "folder_name",
              
            ],
          
        
          
          

          
            "glossary_terms": [
              
                "term",
              
                "definition",
              
                "source_notes",
              
            ],
          
        
          
          

          
            "health_vault_documents": [
              
                "document_name",
              
                "issuing_institution",
              
                "notes",
              
            ],
          
        
          
          

          
            "emergency_medical_cards": [
              
                "full_name",
              
                "blood_type",
              
                "critical_allergies",
              
                "critical_conditions",
              
                "critical_medications",
              
                "emergency_contacts",
              
                "treating_doctor_contact",
              
                "advance_directives_summary",
              
            ],
          
        
          
          

          
            "advance_directives": [
              
                "summary",
              
                "proxy_contact_details",
              
            ],
          
        
          
          

          
            "insurance_policies": [
              
                "provider_name",
              
                "policy_number",
              
                "group_number",
              
                "coverage_type",
              
                "contact_phone",
              
                "claims_contact",
              
                "preauthorisation_notes",
              
            ],
          
        
          
          

          
            "family_groups": [
              
                "group_name",
              
                "invite_code",
              
                "notes",
              
            ],
          
        
          
          

          
            "family_members": [
              
                "display_name",
              
            ],
          
        
          
          

          
        
          
          

          
            "mood_logs": [
              
                "emotion_tags_csv",
              
                "contributing_factors",
              
                "journal_entry",
              
            ],
          
        
          
          

          
            "mental_assessments": [
              
                "responses_json",
              
                "interpretation_notes",
              
            ],
          
        
          
          

          
            "journal_entries": [
              
                "title",
              
                "content",
              
            ],
          
        
          
          

          
            "breathing_sessions": [
              
                "notes",
              
            ],
          
        
          
          

          
            "stress_logs": [
              
                "stressor",
              
                "physical_symptoms",
              
                "coping_strategy_used",
              
                "notes",
              
            ],
          
        
          
          

          
            "cognitive_tests": [
              
                "details_json",
              
            ],
          
        
          
          

          
            "sleep_logs": [
              
                "dream_notes",
              
                "sleep_aids_used",
              
                "disturbances",
              
            ],
          
        
          
          

          
        
          
          

          
            "nap_logs": [
              
                "notes",
              
            ],
          
        
          
          

          
            "menstrual_cycles": [
              
                "notes",
              
            ],
          
        
          
          

          
            "menstrual_day_logs": [
              
                "notes",
              
            ],
          
        
          
          

          
            "fertility_logs": [
              
                "notes",
              
            ],
          
        
          
          

          
            "pregnancies": [
              
                "birth_plan",
              
                "notes",
              
            ],
          
        
          
          

          
            "pregnancy_symptom_logs": [
              
                "notes",
              
            ],
          
        
          
          

          
            "breastfeeding_logs": [
              
                "latch_notes",
              
                "production_notes",
              
            ],
          
        
          
          

          
            "formula_feeding_logs": [
              
                "formula_brand",
              
                "notes",
              
            ],
          
        
          
          

          
            "baby_metrics": [
              
                "notes",
              
            ],
          
        
          
          

          
            "epds_assessments": [
              
                "responses_json",
              
                "notes",
              
            ],
          
        
          
          

          
            "kick_counts": [
              
                "notes",
              
            ],
          
        
          
          

          
            "contraction_sessions": [
              
                "notes",
              
            ],
          
        
          
          

          
        
          
          

          
            "menopause_symptom_logs": [
              
                "notes",
              
            ],
          
        
          
          

          
            "male_reproductive_logs": [
              
                "ipss_responses_json",
              
                "iief5_responses_json",
              
                "notes",
              
            ],
          
        
          
          

          
            "semen_analyses": [
              
                "notes",
              
            ],
          
        
          
          

          
            "sti_tests": [
              
                "tests_performed",
              
                "results_notes",
              
            ],
          
        
          
          

          
            "contraception_logs": [
              
                "notes",
              
            ],
          
        
          
          

          
            "libido_logs": [
              
                "notes",
              
            ],
          
        
          
          

          
            "sexual_activity_logs": [
              
                "notes",
              
            ],
          
        
          
          

          
            "skin_care_logs": [
              
                "products_used",
              
                "breakout_locations",
              
                "notes",
              
            ],
          
        
          
          

          
            "sun_exposure_logs": [
              
                "notes",
              
            ],
          
        
          
          

          
            "mole_lesion_logs": [
              
                "lesion_name",
              
                "abcde_notes",
              
            ],
          
        
          
          

          
            "oral_hygiene_logs": [
              
                "notes",
              
            ],
          
        
          
          

          
            "dental_records": [
              
                "tooth_chart_json",
              
                "notes",
              
            ],
          
        
          
          

          
            "dental_symptoms": [
              
                "tooth_identifier",
              
                "notes",
              
            ],
          
        
          
          

          
            "vision_prescriptions": [
              
                "notes",
              
            ],
          
        
          
          

          
            "eye_symptom_logs": [
              
                "notes",
              
            ],
          
        
          
          

          
            "hearing_test_logs": [
              
                "audiogram_json",
              
                "notes",
              
            ],
          
        
          
          

          
            "tinnitus_logs": [
              
                "pitch_description",
              
                "triggers",
              
                "notes",
              
            ],
          
        
          
          

          
            "noise_exposure_logs": [
              
                "notes",
              
            ],
          
        
          
          

          
            "pain_logs": [
              
                "better_with",
              
                "worse_with",
              
                "medications_taken",
              
                "journal_notes",
              
            ],
          
        
          
          

          
            "injuries": [
              
                "diagnosis",
              
                "initial_treatment",
              
                "notes",
              
            ],
          
        
          
          

          
            "physio_exercises": [
              
                "progression_notes",
              
            ],
          
        
          
          

          
            "ergonomics_logs": [
              
                "workstation_notes",
              
                "posture_notes",
              
            ],
          
        
          
          

          
            "notifications": [
              
                "title",
              
                "message",
              
                "action_link",
              
            ],
          
        
          
          

          
            "export_jobs": [
              
                "included_sections",
              
                "chief_complaint",
              
                "questions_for_doctor",
              
                "error_message",
              
            ],
          
        
          
          

          
            "app_settings": [
              
                "anthropic_api_key_encrypted",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
            "user_physical_baselines": [
              
                "height_cm",
              
                "height_ft",
              
                "height_in",
              
                "weight_kg",
              
                "weight_lb",
              
                "wrist_circumference_cm",
              
            ],
          
        
          
          
          
            "user_lifestyle_baselines": [
              
                "caffeine_servings_per_day",
              
                "typical_stress_level",
              
                "avg_daily_steps_estimate",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "medications": [
              
                "dose_amount",
              
                "frequency_interval_hours",
              
            ],
          
        
          
          
          
        
          
          
          
            "medication_side_effects": [
              
                "severity",
              
            ],
          
        
          
          
          
            "supplements": [
              
                "dose_amount",
              
                "cost_per_dose",
              
                "cycle_on_days",
              
                "cycle_off_days",
              
            ],
          
        
          
          
          
            "supplement_evidence_items": [
              
                "evidence_rating",
              
            ],
          
        
          
          
          
            "workouts": [
              
                "duration_minutes",
              
                "estimated_calories",
              
                "average_rating",
              
            ],
          
        
          
          
          
        
          
          
          
            "workout_exercises": [
              
                "sort_order",
              
                "sets",
              
                "reps",
              
                "rest_seconds",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "workout_sessions": [
              
                "duration_minutes",
              
                "estimated_calories",
              
                "total_volume_kg",
              
                "satisfaction_rating",
              
            ],
          
        
          
          
          
            "strength_sets": [
              
                "set_number",
              
                "reps",
              
                "weight",
              
                "rpe",
              
            ],
          
        
          
          
          
            "cardio_sessions": [
              
                "duration_minutes",
              
                "distance_km",
              
                "avg_heart_rate",
              
                "perceived_effort",
              
                "calories",
              
            ],
          
        
          
          
          
            "recovery_logs": [
              
                "resting_heart_rate",
              
                "hrv_ms",
              
                "stress_level",
              
                "recovery_score",
              
            ],
          
        
          
          
          
            "heat_cold_exposures": [
              
                "duration_minutes",
              
                "temperature_c",
              
            ],
          
        
          
          
          
            "flexibility_assessments": [
              
                "sit_and_reach_score",
              
                "shoulder_mobility_score",
              
                "hip_flexor_score",
              
                "hamstring_score",
              
                "ankle_dorsiflexion_score",
              
            ],
          
        
          
          
          
            "foods": [
              
                "serving_size_g",
              
                "calories",
              
                "protein_g",
              
                "carbs_g",
              
                "sugars_g",
              
                "fat_g",
              
                "saturated_fat_g",
              
                "fibre_g",
              
                "sodium_mg",
              
            ],
          
        
          
          
          
            "recipes": [
              
                "prep_time_minutes",
              
                "cook_time_minutes",
              
                "servings",
              
                "rating",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "meal_items": [
              
                "quantity",
              
                "calories",
              
                "protein_g",
              
                "carbs_g",
              
                "fat_g",
              
            ],
          
        
          
          
          
            "nutrition_targets": [
              
                "bmr",
              
                "tdee",
              
                "calorie_target",
              
                "protein_target_g",
              
                "carb_target_g",
              
                "fat_target_g",
              
            ],
          
        
          
          
          
            "meal_plans": [
              
                "people_count",
              
                "prep_time_minutes_per_day",
              
                "target_calories_per_day",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "grocery_items": [
              
                "quantity",
              
            ],
          
        
          
          
          
            "hydration_logs": [
              
                "volume_ml",
              
            ],
          
        
          
          
          
        
          
          
          
            "ketone_glucose_logs": [
              
                "value",
              
            ],
          
        
          
          
          
        
          
          
          
            "gut_symptom_logs": [
              
                "severity",
              
            ],
          
        
          
          
          
            "health_metrics": [
              
                "value_primary",
              
                "value_secondary",
              
            ],
          
        
          
          
          
            "symptom_logs": [
              
                "severity",
              
                "duration_minutes",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "vaccinations": [
              
                "dose_number",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "habits": [
              
                "times_per_week",
              
                "every_x_days",
              
                "target_count_per_day",
              
                "target_duration_minutes",
              
            ],
          
        
          
          
          
            "habit_logs": [
              
                "count_completed",
              
                "duration_minutes",
              
            ],
          
        
          
          
          
        
          
          
          
            "library_articles": [
              
                "reading_time_minutes",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "mood_logs": [
              
                "mood_score",
              
                "energy_level",
              
                "anxiety_level",
              
            ],
          
        
          
          
          
            "mental_assessments": [
              
                "score_total",
              
            ],
          
        
          
          
          
        
          
          
          
            "breathing_sessions": [
              
                "duration_minutes",
              
            ],
          
        
          
          
          
            "stress_logs": [
              
                "stress_level",
              
            ],
          
        
          
          
          
            "cognitive_tests": [
              
                "score",
              
                "duration_seconds",
              
            ],
          
        
          
          
          
            "sleep_logs": [
              
                "awakenings_count",
              
                "total_sleep_minutes",
              
                "sleep_quality",
              
                "morning_energy",
              
            ],
          
        
          
          
          
            "sleep_environment_logs": [
              
                "temperature_c",
              
                "noise_level",
              
                "light_level",
              
                "bedding_comfort",
              
                "screen_time_before_bed_minutes",
              
            ],
          
        
          
          
          
            "nap_logs": [
              
                "duration_minutes",
              
                "quality",
              
            ],
          
        
          
          
          
        
          
          
          
            "menstrual_day_logs": [
              
                "cramping",
              
                "bloating",
              
            ],
          
        
          
          
          
            "fertility_logs": [
              
                "bbt_c",
              
            ],
          
        
          
          
          
        
          
          
          
            "pregnancy_symptom_logs": [
              
                "nausea",
              
                "vomiting",
              
                "fatigue",
              
                "heartburn",
              
                "swelling",
              
            ],
          
        
          
          
          
            "breastfeeding_logs": [
              
                "duration_minutes",
              
            ],
          
        
          
          
          
            "formula_feeding_logs": [
              
                "volume_ml",
              
            ],
          
        
          
          
          
            "baby_metrics": [
              
                "weight_kg",
              
                "length_cm",
              
                "head_circumference_cm",
              
            ],
          
        
          
          
          
            "epds_assessments": [
              
                "score_total",
              
            ],
          
        
          
          
          
            "kick_counts": [
              
                "kicks_count",
              
            ],
          
        
          
          
          
        
          
          
          
            "contractions": [
              
                "duration_seconds",
              
                "interval_seconds",
              
            ],
          
        
          
          
          
            "menopause_symptom_logs": [
              
                "hot_flush_severity",
              
                "hot_flush_duration_minutes",
              
            ],
          
        
          
          
          
            "male_reproductive_logs": [
              
                "psa",
              
                "ipss_score",
              
                "iief5_score",
              
            ],
          
        
          
          
          
            "semen_analyses": [
              
                "volume_ml",
              
                "concentration_million_per_ml",
              
                "motility_percent",
              
                "morphology_percent",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "libido_logs": [
              
                "libido_score",
              
            ],
          
        
          
          
          
        
          
          
          
            "skin_care_logs": [
              
                "oiliness",
              
                "dryness",
              
                "redness",
              
                "sensitivity",
              
            ],
          
        
          
          
          
            "sun_exposure_logs": [
              
                "uv_index",
              
                "time_outdoors_minutes",
              
                "spf_used",
              
                "vitamin_d_estimate_iu",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "dental_symptoms": [
              
                "severity",
              
            ],
          
        
          
          
          
            "vision_prescriptions": [
              
                "right_sphere",
              
                "right_cylinder",
              
                "right_axis",
              
                "left_sphere",
              
                "left_cylinder",
              
                "left_axis",
              
                "add_power",
              
                "pupillary_distance_mm",
              
            ],
          
        
          
          
          
            "eye_symptom_logs": [
              
                "severity",
              
                "screen_time_minutes",
              
            ],
          
        
          
          
          
        
          
          
          
            "tinnitus_logs": [
              
                "severity",
              
            ],
          
        
          
          
          
            "noise_exposure_logs": [
              
                "estimated_loudness",
              
                "duration_minutes",
              
            ],
          
        
          
          
          
            "pain_logs": [
              
                "severity",
              
            ],
          
        
          
          
          
        
          
          
          
            "physio_exercises": [
              
                "sets",
              
                "reps",
              
            ],
          
        
          
          
          
            "ergonomics_logs": [
              
                "sitting_minutes",
              
                "standing_minutes",
              
                "moving_minutes",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "app_settings": [
              
                "auto_lock_minutes",
              
            ],
          
        
      };

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