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

          
        
          
          

          
            "projects": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "workspaces": [
              
                "name",
              
            ],
          
        
          
          

          
            "llm_providers": [
              
                "name",
              
                "base_url",
              
            ],
          
        
          
          

          
            "llm_models": [
              
                "name",
              
                "model_code",
              
            ],
          
        
          
          

          
            "llm_api_keys": [
              
                "label",
              
                "key_fingerprint",
              
            ],
          
        
          
          

          
            "key_rotation_policies": [
              
                "name",
              
            ],
          
        
          
          

          
            "prompt_templates": [
              
                "name",
              
                "content",
              
            ],
          
        
          
          

          
            "chats": [
              
                "title",
              
            ],
          
        
          
          

          
            "chat_messages": [
              
                "sender_label",
              
                "content_ciphertext",
              
                "content_preview",
              
                "encryption_key_id",
              
            ],
          
        
          
          

          
            "encryption_sessions": [
              
                "session_key_id",
              
            ],
          
        
          
          

          
            "code_repositories": [
              
                "name",
              
                "remote_url",
              
                "default_branch",
              
            ],
          
        
          
          

          
            "code_files": [
              
                "path",
              
                "language",
              
                "content",
              
                "content_hash",
              
            ],
          
        
          
          

          
            "code_change_sets": [
              
                "title",
              
                "summary",
              
            ],
          
        
          
          

          
            "code_patches": [
              
                "file_path",
              
                "diff_text",
              
                "error_message",
              
            ],
          
        
          
          

          
            "build_jobs": [
              
                "name",
              
            ],
          
        
          
          

          
            "build_pipelines": [
              
                "name",
              
                "description",
              
                "config_yaml",
              
            ],
          
        
          
          

          
            "build_artifacts": [
              
                "file_name",
              
                "download_url",
              
                "checksum_sha256",
              
            ],
          
        
          
          

          
            "web_search_queries": [
              
                "query_text",
              
            ],
          
        
          
          

          
            "web_search_results": [
              
                "title",
              
                "url",
              
                "snippet",
              
            ],
          
        
          
          

          
            "system_health_checks": [
              
                "component",
              
                "details",
              
            ],
          
        
          
          

          
            "audit_events": [
              
                "action",
              
                "entity_name",
              
                "entity_key",
              
                "metadata_json",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "llm_models": [
              
                "max_input_tokens",
              
                "max_output_tokens",
              
                "price_per_million_input_tokens",
              
                "price_per_million_output_tokens",
              
            ],
          
        
          
          
          
            "llm_api_keys": [
              
                "requests_per_minute_limit",
              
                "daily_request_limit",
              
            ],
          
        
          
          
          
            "key_rotation_policies": [
              
                "rotate_every_seconds",
              
                "error_threshold",
              
                "cooldown_seconds",
              
            ],
          
        
          
          
          
            "prompt_templates": [
              
                "version",
              
            ],
          
        
          
          
          
        
          
          
          
            "chat_messages": [
              
                "token_count_input",
              
                "token_count_output",
              
            ],
          
        
          
          
          
            "encryption_sessions": [
              
                "key_length_bits",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "web_search_results": [
              
                "rank",
              
            ],
          
        
          
          
          
            "system_health_checks": [
              
                "latency_ms",
              
                "error_rate_percent",
              
            ],
          
        
          
          
          
        
      };

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