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

          
        
          
          

          
        
          
          

          
            "auth_sessions": [
              
                "session_token",
              
                "jwt_identifier",
              
                "ip_address",
              
                "user_agent",
              
            ],
          
        
          
          

          
            "api_keys": [
              
                "key_name",
              
                "key_prefix",
              
                "key_hash",
              
            ],
          
        
          
          

          
            "categories": [
              
                "category_name",
              
                "slug",
              
                "description",
              
            ],
          
        
          
          

          
            "brands": [
              
                "brand_name",
              
                "slug",
              
            ],
          
        
          
          

          
            "suppliers": [
              
                "supplier_name",
              
                "contact_name",
              
                "email",
              
                "phone",
              
                "address",
              
            ],
          
        
          
          

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

          
            "product_variants": [
              
                "variant_name",
              
                "variant_sku",
              
            ],
          
        
          
          

          
            "variant_attributes": [
              
                "attribute_name",
              
                "attribute_value",
              
            ],
          
        
          
          

          
            "seo_entries": [
              
                "target_slug",
              
                "meta_title",
              
                "meta_description",
              
                "canonical_url",
              
            ],
          
        
          
          

          
            "product_reviews": [
              
                "review_title",
              
                "review_body",
              
            ],
          
        
          
          

          
        
          
          

          
        
          
          

          
            "carts": [
              
                "guest_token",
              
            ],
          
        
          
          

          
        
          
          

          
            "coupons": [
              
                "code",
              
            ],
          
        
          
          

          
            "user_addresses": [
              
                "label",
              
                "recipient_name",
              
                "recipient_phone",
              
                "city",
              
                "area",
              
                "street_address",
              
                "landmark",
              
            ],
          
        
          
          

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

          
            "shipping_methods": [
              
                "method_name",
              
            ],
          
        
          
          

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

          
            "order_items": [
              
                "product_name_snapshot",
              
                "sku_snapshot",
              
            ],
          
        
          
          

          
            "payments": [
              
                "transaction_reference",
              
                "provider_payload",
              
            ],
          
        
          
          

          
            "shipments": [
              
                "tracking_number",
              
            ],
          
        
          
          

          
            "ad_placements": [
              
                "placement_name",
              
                "placement_key",
              
                "description",
              
            ],
          
        
          
          

          
            "ads": [
              
                "ad_name",
              
                "creative_text",
              
                "custom_code",
              
                "destination_url",
              
            ],
          
        
          
          

          
            "ad_events": [
              
                "session_token",
              
                "ip_address",
              
                "user_agent",
              
                "referrer_url",
              
            ],
          
        
          
          

          
            "app_settings": [
              
                "settings_key",
              
                "settings_value",
              
                "description",
              
            ],
          
        
          
          

          
            "cms_pages": [
              
                "page_title",
              
                "slug",
              
                "content",
              
            ],
          
        
          
          

          
            "footer_settings": [
              
                "store_description",
              
                "copyright_text",
              
                "footer_banner_text",
              
                "footer_banner_url",
              
            ],
          
        
          
          

          
            "social_links": [
              
                "url",
              
            ],
          
        
          
          

          
            "footer_links": [
              
                "label",
              
                "href",
              
            ],
          
        
          
          

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

          
        
          
          

          
            "push_subscriptions": [
              
                "endpoint",
              
                "p256dh_key",
              
                "auth_key",
              
            ],
          
        
          
          

          
            "notifications": [
              
                "title",
              
                "message",
              
                "deep_link",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "categories": [
              
                "sort_order",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "products": [
              
                "price",
              
                "compare_at_price",
              
                "stock_quantity",
              
                "discount_percent",
              
            ],
          
        
          
          
          
            "product_variants": [
              
                "price",
              
                "compare_at_price",
              
                "stock_quantity",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "product_reviews": [
              
                "rating",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "cart_items": [
              
                "quantity",
              
                "unit_price",
              
            ],
          
        
          
          
          
            "coupons": [
              
                "discount_value",
              
                "minimum_order_amount",
              
                "usage_limit",
              
                "usage_count",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "shipping_methods": [
              
                "base_cost",
              
                "free_shipping_threshold",
              
            ],
          
        
          
          
          
            "orders": [
              
                "subtotal_amount",
              
                "discount_amount",
              
                "shipping_amount",
              
                "tax_amount",
              
                "total_amount",
              
            ],
          
        
          
          
          
            "order_items": [
              
                "unit_price",
              
                "quantity",
              
                "line_total",
              
            ],
          
        
          
          
          
            "payments": [
              
                "amount",
              
            ],
          
        
          
          
          
        
          
          
          
            "ad_placements": [
              
                "sort_order",
              
            ],
          
        
          
          
          
            "ads": [
              
                "impressions_count",
              
                "clicks_count",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "social_links": [
              
                "sort_order",
              
            ],
          
        
          
          
          
            "footer_links": [
              
                "sort_order",
              
            ],
          
        
          
          
          
        
          
          
          
            "payment_icons": [
              
                "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;
    }
  }
}