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

          
            "stores": [
              
                "store_name",
              
                "shopify_domain",
              
                "shopify_storefront_url",
              
                "currency_code",
              
                "primary_locale",
              
                "shopify_api_version",
              
            ],
          
        
          
          

          
            "pages": [
              
                "title",
              
                "slug",
              
                "meta_title",
              
                "meta_description",
              
                "content",
              
            ],
          
        
          
          

          
            "collections": [
              
                "collection_name",
              
                "handle",
              
                "description",
              
            ],
          
        
          
          

          
            "products": [
              
                "product_title",
              
                "handle",
              
                "vendor",
              
                "product_type",
              
                "description",
              
            ],
          
        
          
          

          
            "product_variants": [
              
                "variant_title",
              
                "sku",
              
                "barcode",
              
                "weight_unit",
              
            ],
          
        
          
          

          
            "customers": [
              
                "first_name",
              
                "last_name",
              
                "email",
              
                "phone",
              
                "notes",
              
            ],
          
        
          
          

          
            "addresses": [
              
                "label",
              
                "first_name",
              
                "last_name",
              
                "company",
              
                "address1",
              
                "address2",
              
                "city",
              
                "province",
              
                "postal_code",
              
                "country",
              
                "phone",
              
            ],
          
        
          
          

          
            "orders": [
              
                "order_number",
              
                "currency_code",
              
                "cancel_reason",
              
                "internal_note",
              
            ],
          
        
          
          

          
            "order_items": [
              
                "title",
              
                "fulfillment_service",
              
            ],
          
        
          
          

          
            "fulfillments": [
              
                "tracking_company",
              
                "tracking_number",
              
                "tracking_url",
              
                "note",
              
            ],
          
        
          
          

          
            "payments": [
              
                "currency_code",
              
                "gateway",
              
                "transaction_reference",
              
                "failure_reason",
              
            ],
          
        
          
          

          
            "discount_codes": [
              
                "code",
              
            ],
          
        
          
          

          
            "refunds": [
              
                "currency_code",
              
                "reason",
              
                "note",
              
            ],
          
        
          
          

          
            "inventory_adjustments": [
              
                "reason",
              
            ],
          
        
          
          

          
            "faq_articles": [
              
                "question",
              
                "answer",
              
            ],
          
        
          
          

          
            "chatbot_configs": [
              
                "bot_name",
              
                "model_name",
              
                "system_prompt",
              
                "welcome_message",
              
            ],
          
        
          
          

          
            "chat_sessions": [
              
                "session_key",
              
            ],
          
        
          
          

          
            "chat_messages": [
              
                "sender_display_name",
              
                "message_text",
              
            ],
          
        
          
          

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

          
            "shopify_sync_jobs": [
              
                "error_message",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "products": [
              
                "current_sales_rank",
              
                "total_sales_count",
              
            ],
          
        
          
          
          
            "product_variants": [
              
                "price",
              
                "compare_at_price",
              
                "inventory_quantity",
              
                "weight",
              
            ],
          
        
          
          
          
            "customers": [
              
                "orders_count",
              
                "total_spent",
              
            ],
          
        
          
          
          
        
          
          
          
            "orders": [
              
                "subtotal_price",
              
                "shipping_price",
              
                "tax_price",
              
                "discount_total",
              
                "total_price",
              
            ],
          
        
          
          
          
            "order_items": [
              
                "quantity",
              
                "unit_price",
              
                "line_discount",
              
                "line_total",
              
            ],
          
        
          
          
          
        
          
          
          
            "payments": [
              
                "amount",
              
            ],
          
        
          
          
          
            "discount_codes": [
              
                "value",
              
                "usage_limit",
              
                "used_count",
              
            ],
          
        
          
          
          
            "refunds": [
              
                "amount",
              
            ],
          
        
          
          
          
            "inventory_adjustments": [
              
                "delta_quantity",
              
                "resulting_quantity",
              
            ],
          
        
          
          
          
            "faq_articles": [
              
                "sort_order",
              
            ],
          
        
          
          
          
            "chatbot_configs": [
              
                "temperature",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "shopify_sync_jobs": [
              
                "records_processed",
              
            ],
          
        
      };

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