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

          
            "trust_profiles": [
              
                "risk_flags_summary",
              
            ],
          
        
          
          

          
            "identity_verifications": [
              
                "document_number",
              
                "review_notes",
              
            ],
          
        
          
          

          
            "wallets": [
              
                "wallet_code",
              
                "currency",
              
            ],
          
        
          
          

          
            "wallet_transactions": [
              
                "reference_code",
              
                "counterparty_label",
              
                "memo",
              
            ],
          
        
          
          

          
            "chats": [
              
                "chat_title",
              
            ],
          
        
          
          

          
        
          
          

          
            "messages": [
              
                "text_body",
              
                "link_url",
              
            ],
          
        
          
          

          
            "stores": [
              
                "store_name",
              
                "store_slug",
              
                "description",
              
                "support_phone",
              
                "support_email",
              
            ],
          
        
          
          

          
            "addresses": [
              
                "label",
              
                "recipient_name",
              
                "phone_number",
              
                "country",
              
                "province",
              
                "city",
              
                "district",
              
                "postal_code",
              
                "street_address",
              
            ],
          
        
          
          

          
            "product_categories": [
              
                "category_name",
              
                "category_slug",
              
                "description",
              
            ],
          
        
          
          

          
            "products": [
              
                "product_name",
              
                "sku",
              
                "description",
              
            ],
          
        
          
          

          
            "orders": [
              
                "order_number",
              
                "buyer_note",
              
            ],
          
        
          
          

          
            "order_items": [
              
                "variant_label",
              
            ],
          
        
          
          

          
            "payments": [
              
                "payment_reference",
              
            ],
          
        
          
          

          
            "product_reviews": [
              
                "review_text",
              
            ],
          
        
          
          

          
            "shipments": [
              
                "tracking_number",
              
            ],
          
        
          
          

          
            "posts": [
              
                "caption",
              
            ],
          
        
          
          

          
            "deep_dive_links": [
              
                "title_text",
              
                "summary",
              
            ],
          
        
          
          

          
            "citations": [
              
                "source_title",
              
                "source_url",
              
                "publisher",
              
                "quote_excerpt",
              
                "doi_or_identifier",
              
            ],
          
        
          
          

          
            "post_engagements": [
              
                "comment_text",
              
            ],
          
        
          
          

          
            "rewards": [
              
                "reason_note",
              
            ],
          
        
          
          

          
            "forum_spaces": [
              
                "space_name",
              
                "description",
              
            ],
          
        
          
          

          
            "forum_threads": [
              
                "thread_title",
              
                "thread_body",
              
            ],
          
        
          
          

          
            "forum_posts": [
              
                "body_text",
              
            ],
          
        
          
          

          
            "job_companies": [
              
                "company_name",
              
                "company_legal_name",
              
                "company_website",
              
                "about",
              
            ],
          
        
          
          

          
            "job_listings": [
              
                "job_title",
              
                "location_text",
              
                "description",
              
            ],
          
        
          
          

          
            "job_applications": [
              
                "cover_letter",
              
            ],
          
        
          
          

          
            "user_credentials": [
              
                "title_text",
              
                "issuer_name",
              
                "notes",
              
            ],
          
        
          
          

          
            "affiliate_programs": [
              
                "program_name",
              
                "terms_text",
              
            ],
          
        
          
          

          
            "affiliate_memberships": [
              
                "referral_code",
              
                "notes",
              
            ],
          
        
          
          

          
        
          
          

          
            "geo_rules": [
              
                "rule_name",
              
                "notes",
              
            ],
          
        
          
          

          
            "facta_queries": [
              
                "query_text",
              
            ],
          
        
          
          

          
            "facta_answers": [
              
                "executive_summary",
              
                "ready_to_cite_text",
              
                "neutral_perspective",
              
                "pro_perspective",
              
                "contra_perspective",
              
            ],
          
        
          
          

          
            "subscriptions": [
              
                "billing_cycle",
              
            ],
          
        
          
          

          
            "api_clients": [
              
                "client_name",
              
                "contact_email",
              
                "contact_phone",
              
                "api_key_label",
              
                "notes",
              
            ],
          
        
          
          

          
            "audit_events": [
              
                "entity_name",
              
                "entity_key",
              
                "ip_address",
              
                "user_agent",
              
                "details_json",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
            "trust_profiles": [
              
                "trust_score",
              
            ],
          
        
          
          
          
            "identity_verifications": [
              
                "match_confidence",
              
            ],
          
        
          
          
          
            "wallets": [
              
                "available_balance",
              
                "pending_balance",
              
            ],
          
        
          
          
          
            "wallet_transactions": [
              
                "amount",
              
                "fee_amount",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "addresses": [
              
                "latitude",
              
                "longitude",
              
            ],
          
        
          
          
          
        
          
          
          
            "products": [
              
                "price",
              
                "cost_price",
              
                "stock_quantity",
              
            ],
          
        
          
          
          
            "orders": [
              
                "subtotal_amount",
              
                "shipping_amount",
              
                "total_amount",
              
            ],
          
        
          
          
          
            "order_items": [
              
                "quantity",
              
                "unit_price",
              
                "line_total",
              
            ],
          
        
          
          
          
            "payments": [
              
                "amount",
              
            ],
          
        
          
          
          
            "product_reviews": [
              
                "rating",
              
            ],
          
        
          
          
          
            "shipments": [
              
                "shipping_fee",
              
            ],
          
        
          
          
          
        
          
          
          
            "deep_dive_links": [
              
                "ai_confidence",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "rewards": [
              
                "points_amount",
              
                "cash_value_amount",
              
            ],
          
        
          
          
          
            "forum_spaces": [
              
                "center_latitude",
              
                "center_longitude",
              
                "radius_meters",
              
                "min_trust_score_to_post",
              
            ],
          
        
          
          
          
            "forum_threads": [
              
                "upvotes_count",
              
            ],
          
        
          
          
          
            "forum_posts": [
              
                "upvotes_count",
              
            ],
          
        
          
          
          
        
          
          
          
            "job_listings": [
              
                "salary_min",
              
                "salary_max",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "affiliate_programs": [
              
                "commission_rate_percent",
              
                "min_trust_score_to_join",
              
            ],
          
        
          
          
          
        
          
          
          
            "commissions": [
              
                "gross_profit_amount",
              
                "commission_amount",
              
                "commission_rate_percent",
              
            ],
          
        
          
          
          
            "geo_rules": [
              
                "center_latitude",
              
                "center_longitude",
              
                "radius_meters",
              
            ],
          
        
          
          
          
        
          
          
          
            "facta_answers": [
              
                "truth_score_percent",
              
            ],
          
        
          
          
          
            "subscriptions": [
              
                "price_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;
    }
  }
}