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

          
            "tenants": [
              
                "name",
              
                "slug",
              
                "default_region",
              
                "data_retention_policy",
              
            ],
          
        
          
          

          
            "departments": [
              
                "name",
              
                "path_key",
              
            ],
          
        
          
          

          
            "teams": [
              
                "name",
              
                "slug",
              
            ],
          
        
          
          

          
        
          
          

          
            "identity_providers": [
              
                "name",
              
                "issuer_url",
              
                "client_id",
              
                "sso_metadata_url",
              
            ],
          
        
          
          

          
            "user_identities": [
              
                "external_subject",
              
                "external_email",
              
                "display_name",
              
            ],
          
        
          
          

          
            "policy_rules": [
              
                "name",
              
                "description",
              
                "rego_module",
              
            ],
          
        
          
          

          
            "kms_configs": [
              
                "name",
              
                "key_uri",
              
            ],
          
        
          
          

          
            "conference_templates": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "rooms": [
              
                "name",
              
                "room_key",
              
            ],
          
        
          
          

          
            "room_invitations": [
              
                "invitee_email",
              
                "invite_code",
              
            ],
          
        
          
          

          
            "conferences": [
              
                "conference_key",
              
            ],
          
        
          
          

          
            "participants": [
              
                "display_name",
              
            ],
          
        
          
          

          
            "conference_nodes": [
              
                "name",
              
                "zone",
              
                "endpoint",
              
            ],
          
        
          
          

          
        
          
          

          
            "breakout_rooms": [
              
                "name",
              
                "breakout_key",
              
            ],
          
        
          
          

          
            "chat_channels": [
              
                "name",
              
            ],
          
        
          
          

          
            "chat_messages": [
              
                "message_type",
              
                "body",
              
            ],
          
        
          
          

          
            "files": [
              
                "file_name",
              
                "mime_type",
              
                "storage_uri",
              
                "checksum_sha256",
              
            ],
          
        
          
          

          
        
          
          

          
            "recordings": [
              
                "storage_uri",
              
                "failure_reason",
              
            ],
          
        
          
          

          
            "transcripts": [
              
                "language_code",
              
                "content",
              
            ],
          
        
          
          

          
            "canvas_documents": [
              
                "name",
              
                "snapshot_uri",
              
            ],
          
        
          
          

          
            "canvas_events": [
              
                "payload",
              
            ],
          
        
          
          

          
            "layout_models": [
              
                "name",
              
                "model_version",
              
                "artifact_uri",
              
            ],
          
        
          
          

          
            "layout_preferences": [
              
                "value",
              
            ],
          
        
          
          

          
            "federated_learning_updates": [
              
                "gradient_blob_uri",
              
                "validation_notes",
              
            ],
          
        
          
          

          
            "ai_companion_sessions": [
              
                "system_prompt_version",
              
            ],
          
        
          
          

          
            "knowledge_graph_items": [
              
                "title",
              
                "details",
              
            ],
          
        
          
          

          
            "external_integrations": [
              
                "name",
              
                "auth_reference",
              
            ],
          
        
          
          

          
            "tasks": [
              
                "external_task_key",
              
                "title",
              
                "description",
              
                "failure_reason",
              
            ],
          
        
          
          

          
            "courses": [
              
                "name",
              
                "course_code",
              
                "description",
              
            ],
          
        
          
          

          
        
          
          

          
            "assignments": [
              
                "title",
              
                "instructions",
              
            ],
          
        
          
          

          
            "submissions": [
              
                "student_note",
              
            ],
          
        
          
          

          
            "quizzes": [
              
                "title",
              
                "h5p_reference",
              
            ],
          
        
          
          

          
            "quiz_results": [
              
                "answers_payload",
              
            ],
          
        
          
          

          
            "marketplace_apps": [
              
                "name",
              
                "description",
              
                "version",
              
                "wasm_artifact_uri",
              
            ],
          
        
          
          

          
            "app_installations": [
              
                "disable_reason",
              
            ],
          
        
          
          

          
            "app_crash_reports": [
              
                "client_platform",
              
                "client_version",
              
                "stacktrace",
              
                "context_payload",
              
            ],
          
        
          
          

          
            "audit_events": [
              
                "action",
              
                "target_type",
              
                "target_key",
              
                "ip_address",
              
                "user_agent",
              
                "details",
              
            ],
          
        
          
          

          
            "data_subject_requests": [
              
                "notes",
              
            ],
          
        
          
          

          
            "service_incidents": [
              
                "title",
              
                "summary",
              
                "rca",
              
            ],
          
        
          
          

          
            "deployment_changes": [
              
                "service_name",
              
                "git_ref",
              
                "diff_summary",
              
            ],
          
        
          
          

          
            "feature_flags": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "quality_reports": [
              
                "raw_stats",
              
            ],
          
        
          
          

          
            "event_streams": [
              
                "name",
              
                "subject_or_topic",
              
            ],
          
        
          
          

          
            "conference_events": [
              
                "event_key",
              
                "payload",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "teams": [
              
                "always_on_state_retention_days",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "conference_templates": [
              
                "max_participants",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "conferences": [
              
                "participant_limit",
              
            ],
          
        
          
          
          
            "participants": [
              
                "network_score",
              
            ],
          
        
          
          
          
            "conference_nodes": [
              
                "cpu_utilization",
              
                "memory_utilization",
              
                "current_conferences",
              
            ],
          
        
          
          
          
        
          
          
          
            "breakout_rooms": [
              
                "target_participants",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "files": [
              
                "size_mb",
              
            ],
          
        
          
          
          
        
          
          
          
            "recordings": [
              
                "duration_minutes",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "layout_models": [
              
                "rollback_trigger_rate",
              
            ],
          
        
          
          
          
        
          
          
          
            "federated_learning_updates": [
              
                "privacy_budget",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "assignments": [
              
                "max_score",
              
            ],
          
        
          
          
          
            "submissions": [
              
                "score",
              
            ],
          
        
          
          
          
        
          
          
          
            "quiz_results": [
              
                "score",
              
            ],
          
        
          
          
          
            "marketplace_apps": [
              
                "reliability_score",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "feature_flags": [
              
                "rollout_percentage",
              
            ],
          
        
          
          
          
            "quality_reports": [
              
                "packet_loss_percent",
              
                "rtt_ms",
              
                "jitter_ms",
              
                "send_bitrate_kbps",
              
                "recv_bitrate_kbps",
              
            ],
          
        
          
          
          
            "event_streams": [
              
                "retention_days",
              
            ],
          
        
          
          
          
        
      };

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