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

          
            "workspaces": [
              
                "name",
              
                "billing_email",
              
            ],
          
        
          
          

          
            "user_settings": [
              
                "time_zone",
              
                "locale",
              
                "preferred_voice",
              
            ],
          
        
          
          

          
            "assistant_profiles": [
              
                "name",
              
                "system_prompt",
              
                "model_name",
              
            ],
          
        
          
          

          
            "conversations": [
              
                "title",
              
            ],
          
        
          
          

          
            "messages": [
              
                "content",
              
                "content_format",
              
                "tool_name",
              
                "tool_call_key",
              
            ],
          
        
          
          

          
            "voice_sessions": [
              
                "stt_provider",
              
                "tts_provider",
              
                "detected_language",
              
                "last_error",
              
            ],
          
        
          
          

          
            "tool_providers": [
              
                "name",
              
                "base_url",
              
                "docs_url",
              
            ],
          
        
          
          

          
            "tools": [
              
                "name",
              
                "slug",
              
                "description",
              
            ],
          
        
          
          

          
            "tool_actions": [
              
                "name",
              
                "action_key",
              
                "input_schema",
              
                "output_schema",
              
            ],
          
        
          
          

          
            "integrations": [
              
                "account_label",
              
                "scopes",
              
            ],
          
        
          
          

          
            "memory_items": [
              
                "key",
              
                "value",
              
            ],
          
        
          
          

          
            "tasks": [
              
                "title",
              
                "goal",
              
            ],
          
        
          
          

          
            "task_steps": [
              
                "title",
              
                "details",
              
                "input_payload",
              
                "output_payload",
              
                "error_message",
              
            ],
          
        
          
          

          
            "tool_runs": [
              
                "input_payload",
              
                "output_payload",
              
                "logs",
              
                "error_message",
              
            ],
          
        
          
          

          
            "confirmations": [
              
                "summary",
              
                "risk_notes",
              
                "user_response",
              
            ],
          
        
          
          

          
            "meetings": [
              
                "title",
              
                "join_url",
              
                "transcript",
              
                "summary",
              
            ],
          
        
          
          

          
            "calendar_events": [
              
                "external_event_key",
              
                "title",
              
                "location",
              
                "description",
              
            ],
          
        
          
          

          
            "contacts": [
              
                "display_name",
              
                "email",
              
                "phone",
              
                "time_zone",
              
                "notes",
              
            ],
          
        
          
          

          
            "outbound_messages": [
              
                "subject",
              
                "body",
              
                "provider_message_key",
              
            ],
          
        
          
          

          
            "travel_requests": [
              
                "origin",
              
                "destination",
              
                "preferences",
              
            ],
          
        
          
          

          
            "travel_bookings": [
              
                "provider",
              
                "external_booking_key",
              
                "currency",
              
                "details",
              
            ],
          
        
          
          

          
            "payment_transactions": [
              
                "currency",
              
                "merchant",
              
                "description",
              
                "external_transaction_key",
              
            ],
          
        
          
          

          
            "native_app_checks": [
              
                "platform",
              
                "notes",
              
            ],
          
        
          
          

          
            "audit_logs": [
              
                "event_summary",
              
                "event_payload",
              
                "ip_address",
              
                "user_agent",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
            "user_settings": [
              
                "speech_rate",
              
                "speech_pitch",
              
                "auto_archive_days",
              
            ],
          
        
          
          
          
            "assistant_profiles": [
              
                "temperature",
              
                "max_output_tokens",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "memory_items": [
              
                "confidence",
              
                "use_count",
              
            ],
          
        
          
          
          
        
          
          
          
            "task_steps": [
              
                "step_number",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "travel_requests": [
              
                "travelers_count",
              
                "max_budget",
              
            ],
          
        
          
          
          
            "travel_bookings": [
              
                "amount",
              
            ],
          
        
          
          
          
            "payment_transactions": [
              
                "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}%` }
                )
              )),
            ],
          };

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