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

          
            "assets": [
              
                "name",
              
                "environment",
              
                "ip_address",
              
                "hostname",
              
                "os",
              
                "cloud_provider",
              
            ],
          
        
          
          

          
            "data_sources": [
              
                "name",
              
                "connector_type",
              
                "endpoint_url",
              
                "auth_method",
              
                "notes",
              
            ],
          
        
          
          

          
            "ingestion_pipelines": [
              
                "name",
              
                "kafka_topic",
              
                "data_lake_path",
              
            ],
          
        
          
          

          
            "telemetry_events": [
              
                "summary",
              
                "raw_payload",
              
                "hash",
              
            ],
          
        
          
          

          
            "ai_models": [
              
                "name",
              
                "version",
              
                "framework",
              
                "artifact_uri",
              
                "description",
              
            ],
          
        
          
          

          
            "detections": [
              
                "title",
              
                "evidence",
              
            ],
          
        
          
          

          
            "incidents": [
              
                "name",
              
                "summary",
              
            ],
          
        
          
          

          
            "response_playbooks": [
              
                "name",
              
                "trigger_conditions",
              
                "steps",
              
                "description",
              
            ],
          
        
          
          

          
            "response_actions": [
              
                "target",
              
                "action_result",
              
            ],
          
        
          
          

          
            "soc_agents": [
              
                "name",
              
                "capabilities",
              
            ],
          
        
          
          

          
            "threat_actors": [
              
                "name",
              
                "origin_country",
              
                "aliases",
              
                "profile",
              
            ],
          
        
          
          

          
            "threat_indicators": [
              
                "indicator_value",
              
                "source",
              
                "context",
              
            ],
          
        
          
          

          
            "threat_campaigns": [
              
                "name",
              
                "summary",
              
            ],
          
        
          
          

          
            "attack_map_events": [
              
                "source_country",
              
                "source_ip",
              
                "destination_country",
              
                "destination_ip",
              
            ],
          
        
          
          

          
            "risk_assessments": [
              
                "top_risks",
              
                "recommendations",
              
            ],
          
        
          
          

          
            "simulation_labs": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "simulation_runs": [
              
                "findings",
              
            ],
          
        
          
          

          
            "infrastructure_clusters": [
              
                "name",
              
                "region",
              
                "provider",
              
                "api_gateway_url",
              
            ],
          
        
          
          

          
            "edge_sensors": [
              
                "name",
              
                "location",
              
                "site",
              
                "hardware_model",
              
                "firmware_version",
              
            ],
          
        
          
          

          
            "reports": [
              
                "name",
              
                "content",
              
            ],
          
        
          
          

          
            "ai_recommendations": [
              
                "title",
              
                "details",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
            "data_sources": [
              
                "poll_interval_seconds",
              
            ],
          
        
          
          
          
            "ingestion_pipelines": [
              
                "throughput_eps",
              
                "error_rate_percent",
              
            ],
          
        
          
          
          
        
          
          
          
            "ai_models": [
              
                "threshold",
              
            ],
          
        
          
          
          
            "detections": [
              
                "confidence",
              
                "risk_score",
              
            ],
          
        
          
          
          
            "incidents": [
              
                "business_impact_score",
              
            ],
          
        
          
          
          
            "response_playbooks": [
              
                "expected_duration_minutes",
              
            ],
          
        
          
          
          
        
          
          
          
            "soc_agents": [
              
                "actions_success_rate",
              
            ],
          
        
          
          
          
            "threat_actors": [
              
                "threat_level",
              
            ],
          
        
          
          
          
        
          
          
          
            "threat_campaigns": [
              
                "global_risk_score",
              
            ],
          
        
          
          
          
            "attack_map_events": [
              
                "latitude",
              
                "longitude",
              
                "risk_score",
              
            ],
          
        
          
          
          
            "risk_assessments": [
              
                "overall_risk_score",
              
            ],
          
        
          
          
          
            "simulation_labs": [
              
                "max_duration_minutes",
              
            ],
          
        
          
          
          
            "simulation_runs": [
              
                "success_score",
              
            ],
          
        
          
          
          
            "infrastructure_clusters": [
              
                "cpu_capacity",
              
                "gpu_capacity",
              
                "storage_capacity_tb",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "ai_recommendations": [
              
                "estimated_risk_reduction",
              
            ],
          
        
      };

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