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 ) {
    try {
      if (!searchQuery) {
        throw new ValidationError('iam.errors.searchQueryRequired');
      }
      const tableColumns = {
        
          
          

          
            "users": [
              
                "firstName",
              
                "lastName",
              
                "phoneNumber",
              
                "email",
              
            ],
          
        
          
          
          
          

          
            "developer_api_keys": [
              
                "name",
              
                "key_prefix",
              
                "key_hash",
              
            ],
          
        
          
          

          
            "addresses": [
              
                "label",
              
                "recipient_name",
              
                "phone",
              
                "country",
              
                "governorate",
              
                "city",
              
                "district",
              
                "street_address",
              
                "postal_code",
              
            ],
          
        
          
          

          
            "categories": [
              
                "name_ar",
              
                "name_en",
              
                "slug",
              
                "description_ar",
              
                "description_en",
              
            ],
          
        
          
          

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

          
            "suppliers": [
              
                "name",
              
                "email",
              
                "phone",
              
                "address",
              
            ],
          
        
          
          

          
            "products": [
              
                "name_ar",
              
                "name_en",
              
                "slug",
              
                "short_description_ar",
              
                "short_description_en",
              
                "description_ar",
              
                "description_en",
              
                "sku",
              
                "barcode",
              
            ],
          
        
          
          

          
            "product_variants": [
              
                "name",
              
                "sku",
              
                "attributes_json",
              
            ],
          
        
          
          

          
            "collections": [
              
                "name_ar",
              
                "name_en",
              
                "slug",
              
                "description_ar",
              
                "description_en",
              
            ],
          
        
          
          

          
            "product_reviews": [
              
                "title",
              
                "content",
              
            ],
          
        
          
          

          
        
          
          

          
            "compare_lists": [
              
                "name",
              
            ],
          
        
          
          

          
        
          
          

          
            "carts": [
              
                "session_key",
              
            ],
          
        
          
          

          
        
          
          

          
            "orders": [
              
                "order_number",
              
                "customer_note",
              
            ],
          
        
          
          

          
            "order_items": [
              
                "product_name_snapshot",
              
            ],
          
        
          
          

          
            "shipping_carriers": [
              
                "name",
              
                "tracking_url_template",
              
                "support_phone",
              
            ],
          
        
          
          

          
            "shipments": [
              
                "tracking_number",
              
            ],
          
        
          
          

          
            "payments": [
              
                "provider_reference",
              
            ],
          
        
          
          

          
            "coupons": [
              
                "code",
              
            ],
          
        
          
          

          
        
          
          

          
        
          
          

          
            "point_ledger_entries": [
              
                "note",
              
            ],
          
        
          
          

          
            "frequently_bought_together_groups": [
              
                "name",
              
            ],
          
        
          
          

          
        
          
          

          
            "ad_placements": [
              
                "key",
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "ads": [
              
                "name",
              
                "promotional_text",
              
                "custom_code",
              
                "destination_url",
              
            ],
          
        
          
          

          
            "ad_events": [
              
                "page_path",
              
                "referrer",
              
                "user_agent",
              
                "ip_hash",
              
            ],
          
        
          
          

          
            "site_settings": [
              
                "store_name",
              
                "default_language",
              
                "default_currency",
              
                "adsense_head_code",
              
                "footer_bottom_text",
              
                "footer_partner_banner_text",
              
                "footer_partner_banner_url",
              
            ],
          
        
          
          

          
            "footer_content_blocks": [
              
                "store_description_ar",
              
                "store_description_en",
              
            ],
          
        
          
          

          
            "social_links": [
              
                "url",
              
            ],
          
        
          
          

          
            "footer_links": [
              
                "label_ar",
              
                "label_en",
              
                "href",
              
            ],
          
        
          
          

          
            "payment_badges": [
              
                "label",
              
            ],
          
        
          
          

          
            "newsletter_subscribers": [
              
                "email",
              
                "source",
              
            ],
          
        
          
          

          
            "cms_pages": [
              
                "title_ar",
              
                "title_en",
              
                "content_ar",
              
                "content_en",
              
            ],
          
        
          
          

          
            "push_notifications": [
              
                "title",
              
                "body",
              
                "target_url",
              
            ],
          
        
          
          

          
            "push_subscriptions": [
              
                "endpoint",
              
                "p256dh",
              
                "auth",
              
            ],
          
        
          
          

          
            "seo_entries": [
              
                "entity_key",
              
                "meta_title_ar",
              
                "meta_title_en",
              
                "meta_description_ar",
              
                "meta_description_en",
              
                "canonical_url",
              
                "open_graph_image_url",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
            "categories": [
              
                "sort_order",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "products": [
              
                "price_iqd",
              
                "compare_at_price_iqd",
              
                "cost_iqd",
              
                "stock_on_hand",
              
                "low_stock_threshold",
              
            ],
          
        
          
          
          
            "product_variants": [
              
                "price_iqd",
              
                "stock_on_hand",
              
            ],
          
        
          
          
          
            "collections": [
              
                "sort_order",
              
            ],
          
        
          
          
          
            "product_reviews": [
              
                "rating",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "carts": [
              
                "subtotal_iqd",
              
                "discount_total_iqd",
              
                "shipping_total_iqd",
              
                "grand_total_iqd",
              
            ],
          
        
          
          
          
            "cart_items": [
              
                "quantity",
              
                "unit_price_iqd",
              
                "line_total_iqd",
              
            ],
          
        
          
          
          
            "orders": [
              
                "subtotal_iqd",
              
                "discount_total_iqd",
              
                "shipping_total_iqd",
              
                "grand_total_iqd",
              
            ],
          
        
          
          
          
            "order_items": [
              
                "unit_price_iqd",
              
                "quantity",
              
                "line_total_iqd",
              
            ],
          
        
          
          
          
        
          
          
          
            "shipments": [
              
                "shipping_cost_iqd",
              
            ],
          
        
          
          
          
            "payments": [
              
                "amount_iqd",
              
            ],
          
        
          
          
          
            "coupons": [
              
                "discount_value",
              
                "min_order_total_iqd",
              
                "usage_limit_total",
              
                "usage_limit_per_user",
              
            ],
          
        
          
          
          
        
          
          
          
            "loyalty_settings": [
              
                "earn_rate_percent",
              
                "redeem_value_per_point_iqd",
              
                "min_points_to_redeem",
              
            ],
          
        
          
          
          
            "point_ledger_entries": [
              
                "points",
              
            ],
          
        
          
          
          
        
          
          
          
            "frequently_bought_together_items": [
              
                "sort_order",
              
                "bundle_discount_percent",
              
            ],
          
        
          
          
          
            "ad_placements": [
              
                "sort_order",
              
            ],
          
        
          
          
          
            "ads": [
              
                "impressions_count",
              
                "clicks_count",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "social_links": [
              
                "sort_order",
              
            ],
          
        
          
          
          
            "footer_links": [
              
                "sort_order",
              
            ],
          
        
          
          
          
            "payment_badges": [
              
                "sort_order",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
      };

      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}%` }
                )
              )),
            ],
          };

          

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