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

          
            "tutor_profiles": [
              
                "headline",
              
                "institution_name",
              
                "degree_qualification",
              
                "verification_note",
              
                "jitsi_meet_meeting_id",
              
                "jitsi_meet_password",
              
                "availability_json",
              
            ],
          
        
          
          

          
            "learner_profiles": [
              
                "availability_json",
              
            ],
          
        
          
          

          
            "subject_categories": [
              
                "name_bn",
              
                "name_en",
              
                "icon_key",
              
            ],
          
        
          
          

          
            "subjects": [
              
                "name",
              
                "name_bn",
              
            ],
          
        
          
          

          
            "languages": [
              
                "name",
              
                "code",
              
            ],
          
        
          
          

          
            "gigs": [
              
                "title",
              
                "description",
              
            ],
          
        
          
          

          
            "gig_levels": [
              
                "name",
              
                "description",
              
                "deliverables_json",
              
            ],
          
        
          
          

          
            "tags": [
              
                "label",
              
            ],
          
        
          
          

          
            "bookings": [
              
                "level_name",
              
                "deliverable_notes",
              
                "revision_reason",
              
                "jitsi_meet_meeting_id",
              
                "jitsi_meet_password",
              
                "admin_note",
              
            ],
          
        
          
          

          
            "conversations": [
              
                "last_message",
              
            ],
          
        
          
          

          
            "messages": [
              
                "content",
              
                "file_url",
              
                "file_name",
              
            ],
          
        
          
          

          
            "reviews": [
              
                "review_text",
              
                "tutor_response",
              
            ],
          
        
          
          

          
            "notes": [
              
                "tutor_private_notes",
              
                "learner_private_notes",
              
                "shared_notes",
              
                "session_summary",
              
            ],
          
        
          
          

          
            "disputes": [
              
                "reason",
              
                "description",
              
                "admin_notes",
              
            ],
          
        
          
          

          
            "notifications": [
              
                "title",
              
                "body",
              
                "link",
              
            ],
          
        
          
          

          
            "platform_config": [
              
                "maintenance_message",
              
                "announcement_banner_text",
              
                "jitsi_sdk_key",
              
                "jitsi_sdk_secret",
              
            ],
          
        
          
          

          
            "admin_audit_logs": [
              
                "target_entity",
              
                "target_id",
              
                "details",
              
            ],
          
        
          
          

          
            "user_login_history": [
              
                "device_label",
              
                "ip_address",
              
            ],
          
        
          
          

          
            "invites": [
              
                "message",
              
            ],
          
        
          
          

          
            "spaces": [
              
                "name",
              
                "name_bn",
              
                "description",
              
            ],
          
        
          
          

          
        
          
          

          
            "community_posts": [
              
                "title",
              
                "body",
              
                "image_url",
              
                "resource_url",
              
                "poll_options_json",
              
            ],
          
        
          
          

          
            "community_comments": [
              
                "body",
              
            ],
          
        
          
          

          
        
          
          

          
            "community_reports": [
              
                "content_id",
              
                "reason",
              
                "details",
              
            ],
          
        
          
          

          
            "weekly_challenges": [
              
                "name",
              
                "description",
              
                "tasks_json",
              
                "reward_badge_key",
              
            ],
          
        
          
          

          
        
          
          

          
            "user_gamification": [
              
                "daily_activity_json",
              
            ],
          
        
          
          

          
            "badges": [
              
                "badge_key",
              
                "name_bn",
              
                "name_en",
              
                "description",
              
            ],
          
        
          
          

          
            "user_badges": [
              
                "context",
              
            ],
          
        
          
          

          
            "study_groups": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
        
          
          

          
            "study_group_posts": [
              
                "title",
              
                "body",
              
            ],
          
        
          
          

          
            "study_group_messages": [
              
                "content",
              
                "file_name",
              
                "file_url",
              
            ],
          
        
          
          

          
            "study_group_resources": [
              
                "title",
              
                "url",
              
                "notes",
              
            ],
          
        
          
          

          
            "live_events": [
              
                "title",
              
                "description",
              
                "meeting_link",
              
                "recording_link",
              
            ],
          
        
          
          

          
        
          
          

          
            "certificates": [
              
                "subject_label",
              
                "level_label",
              
                "certificate_html",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
            "tutor_profiles": [
              
                "graduation_year",
              
                "rating",
              
                "total_sessions",
              
                "total_reviews",
              
                "response_rate",
              
                "response_time_hours",
              
                "max_concurrent_bookings",
              
            ],
          
        
          
          
          
        
          
          
          
            "subject_categories": [
              
                "seed_tutor_count",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "gigs": [
              
                "impressions",
              
                "total_orders",
              
                "rating",
              
            ],
          
        
          
          
          
            "gig_levels": [
              
                "level_number",
              
                "price",
              
                "duration_minutes",
              
            ],
          
        
          
          
          
        
          
          
          
            "bookings": [
              
                "level_number",
              
                "price",
              
                "platform_fee",
              
                "tutor_payout",
              
                "revision_count",
              
            ],
          
        
          
          
          
            "conversations": [
              
                "tutor_unread_count",
              
                "learner_unread_count",
              
            ],
          
        
          
          
          
        
          
          
          
            "reviews": [
              
                "rating",
              
                "communication_rating",
              
                "knowledge_rating",
              
                "punctuality_rating",
              
                "value_rating",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "platform_config": [
              
                "platform_fee_percent",
              
                "auto_release_days",
              
                "max_revision_count",
              
                "min_review_length",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "spaces": [
              
                "unread_seed_count",
              
            ],
          
        
          
          
          
        
          
          
          
            "community_posts": [
              
                "like_count",
              
                "love_count",
              
                "insightful_count",
              
                "comment_count",
              
            ],
          
        
          
          
          
            "community_comments": [
              
                "like_count",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "weekly_challenges": [
              
                "reward_points",
              
            ],
          
        
          
          
          
            "challenge_participations": [
              
                "progress_value",
              
                "target_value",
              
            ],
          
        
          
          
          
            "user_gamification": [
              
                "points_total",
              
                "streak_days",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "study_groups": [
              
                "member_limit",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "live_events": [
              
                "capacity",
              
                "price_amount",
              
            ],
          
        
          
          
          
        
          
          
          
        
      };

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