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": [
              
                "legal_name",
              
                "trade_name",
              
                "tax_identifier",
              
                "country_code",
              
                "timezone",
              
            ],
          
        
          
          

          
        
          
          

          
            "service_types": [
              
                "name",
              
                "code",
              
                "description",
              
            ],
          
        
          
          

          
            "authentication_methods": [
              
                "name",
              
                "code",
              
            ],
          
        
          
          

          
            "service_auth_policies": [
              
                "name",
              
            ],
          
        
          
          

          
            "document_categories": [
              
                "name",
              
                "code",
              
                "description",
              
            ],
          
        
          
          

          
            "document_types": [
              
                "name",
              
                "code",
              
                "description",
              
            ],
          
        
          
          

          
            "document_template_variables": [
              
                "name",
              
                "key",
              
                "help_text",
              
            ],
          
        
          
          

          
            "document_templates": [
              
                "title",
              
                "version_label",
              
                "template_body",
              
            ],
          
        
          
          

          
            "workflow_definitions": [
              
                "name",
              
                "code",
              
            ],
          
        
          
          

          
            "workflow_steps": [
              
                "name",
              
                "code",
              
            ],
          
        
          
          

          
            "price_lists": [
              
                "name",
              
                "currency",
              
            ],
          
        
          
          

          
        
          
          

          
            "locations": [
              
                "name",
              
                "code",
              
            ],
          
        
          
          

          
            "contract_folders": [
              
                "title",
              
                "service_warning",
              
            ],
          
        
          
          

          
            "contract_documents": [
              
                "title",
              
                "content_hash",
              
            ],
          
        
          
          

          
            "contract_data_fields": [
              
                "name",
              
                "key",
              
                "value_text",
              
            ],
          
        
          
          

          
            "contract_participants": [
              
                "display_name",
              
                "email",
              
                "phone_e164",
              
            ],
          
        
          
          

          
            "participant_invitations": [
              
                "invite_token",
              
            ],
          
        
          
          

          
            "payments": [
              
                "payment_reference",
              
                "currency",
              
            ],
          
        
          
          

          
            "payment_shares": [
              
                "pay_link_token",
              
            ],
          
        
          
          

          
        
          
          

          
            "authentication_attempts": [
              
                "provider_reference",
              
                "failure_reason",
              
            ],
          
        
          
          

          
            "id_verification_artifacts": [
              
                "quality_notes",
              
            ],
          
        
          
          

          
            "bank_verifications": [
              
                "bank_name",
              
                "account_identifier",
              
            ],
          
        
          
          

          
            "notification_records": [
              
                "record_hash",
              
            ],
          
        
          
          

          
            "notification_record_items": [
              
                "evidence_reference",
              
            ],
          
        
          
          

          
            "signing_actions": [
              
                "signature_hash",
              
            ],
          
        
          
          

          
            "document_revisions": [
              
                "change_summary",
              
                "content_hash",
              
            ],
          
        
          
          

          
            "revision_approvals": [
              
                "comment",
              
            ],
          
        
          
          

          
            "revocation_requests": [
              
                "reason",
              
            ],
          
        
          
          

          
            "support_tickets": [
              
                "subject",
              
                "description",
              
            ],
          
        
          
          

          
            "support_ticket_messages": [
              
                "message",
              
            ],
          
        
          
          

          
            "ai_contract_classifications": [
              
                "model_name",
              
                "predicted_category",
              
                "predicted_document_type",
              
                "disallow_reason",
              
            ],
          
        
          
          

          
            "disallowed_contract_rules": [
              
                "name",
              
                "rule_code",
              
                "description",
              
            ],
          
        
          
          

          
            "service_suitability_rules": [
              
                "name",
              
                "condition_text",
              
                "message",
              
            ],
          
        
          
          

          
            "audit_events": [
              
                "event_type",
              
                "event_summary",
              
                "source_ip",
              
                "user_agent",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "service_auth_policies": [
              
                "min_methods_required",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "workflow_definitions": [
              
                "default_deadline_hours",
              
            ],
          
        
          
          
          
            "workflow_steps": [
              
                "step_order",
              
            ],
          
        
          
          
          
        
          
          
          
            "price_rules": [
              
                "min_participants",
              
                "max_participants",
              
                "price_amount",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "contract_documents": [
              
                "current_revision_number",
              
            ],
          
        
          
          
          
            "contract_data_fields": [
              
                "value_number",
              
            ],
          
        
          
          
          
        
          
          
          
            "participant_invitations": [
              
                "send_count",
              
            ],
          
        
          
          
          
            "payments": [
              
                "total_amount",
              
            ],
          
        
          
          
          
            "payment_shares": [
              
                "amount_due",
              
                "amount_paid",
              
            ],
          
        
          
          
          
            "authentication_sessions": [
              
                "attempt_count",
              
            ],
          
        
          
          
          
        
          
          
          
            "id_verification_artifacts": [
              
                "match_score",
              
            ],
          
        
          
          
          
            "bank_verifications": [
              
                "expected_amount",
              
                "reported_amount",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "signing_actions": [
              
                "revision_number",
              
            ],
          
        
          
          
          
            "document_revisions": [
              
                "revision_number",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "ai_contract_classifications": [
              
                "confidence",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
      };

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