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

          
            "creator_profiles": [
              
                "handle",
              
                "slogan",
              
                "about",
              
                "business_email",
              
                "support_email",
              
                "preferred_language",
              
                "category_tags",
              
            ],
          
        
          
          

          
            "fan_profiles": [
              
                "nickname",
              
                "bio",
              
            ],
          
        
          
          

          
        
          
          

          
            "theme_profiles": [
              
                "theme_name",
              
                "primary_color_hex",
              
                "accent_color_hex",
              
                "neon_glow_color_hex",
              
                "adult_primary_color_hex",
              
                "adult_accent_color_hex",
              
            ],
          
        
          
          

          
            "profile_styles": [
              
                "style_name",
              
                "username_color_hex",
              
                "bio_font_family",
              
                "panel_order_json",
              
                "pronouns_text",
              
                "custom_css",
              
            ],
          
        
          
          

          
            "discovery_items": [
              
                "title",
              
                "subtitle",
              
            ],
          
        
          
          

          
            "streams": [
              
                "title",
              
                "description",
              
                "stream_key_hint",
              
            ],
          
        
          
          

          
            "videos": [
              
                "title",
              
                "description",
              
            ],
          
        
          
          

          
            "comments": [
              
                "target_key",
              
                "body",
              
            ],
          
        
          
          

          
            "playlists": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "playlist_items": [
              
                "item_key",
              
            ],
          
        
          
          

          
            "tip_pages": [
              
                "slug",
              
                "headline",
              
                "thank_you_message",
              
                "background_value",
              
                "accent_color_hex",
              
                "tts_voice",
              
            ],
          
        
          
          

          
            "tips": [
              
                "currency",
              
                "message",
              
            ],
          
        
          
          

          
            "alert_profiles": [
              
                "profile_name",
              
                "brand_primary_hex",
              
                "brand_accent_hex",
              
                "tts_voice",
              
            ],
          
        
          
          

          
            "alerts": [
              
                "title",
              
                "body",
              
                "currency",
              
            ],
          
        
          
          

          
            "overlay_profiles": [
              
                "name",
              
                "access_token",
              
                "canvas_settings_json",
              
            ],
          
        
          
          

          
            "widget_catalog_items": [
              
                "name",
              
                "icon_name",
              
                "author_name",
              
                "description",
              
                "schema_json",
              
            ],
          
        
          
          

          
            "overlay_widgets": [
              
                "instance_name",
              
                "config_json",
              
            ],
          
        
          
          

          
            "merch_stores": [
              
                "store_name",
              
                "store_description",
              
                "policies_text",
              
            ],
          
        
          
          

          
            "products": [
              
                "name",
              
                "description",
              
                "currency",
              
            ],
          
        
          
          

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

          
            "orders": [
              
                "currency",
              
            ],
          
        
          
          

          
            "order_items": [
              
                "product_name_snapshot",
              
            ],
          
        
          
          

          
            "shipping_profiles": [
              
                "profile_name",
              
                "origin_country",
              
                "origin_region",
              
                "origin_postal_code",
              
                "rules_json",
              
            ],
          
        
          
          

          
            "private_mailboxes": [
              
                "public_label",
              
            ],
          
        
          
          

          
            "messages": [
              
                "subject",
              
                "body",
              
            ],
          
        
          
          

          
            "reports": [
              
                "target_key",
              
                "details",
              
            ],
          
        
          
          

          
            "demo_wallets": [
              
                "currency",
              
            ],
          
        
          
          

          
            "wallet_transactions": [
              
                "currency",
              
                "reference_key",
              
                "note",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
            "fan_profiles": [
              
                "xp_coins_balance",
              
            ],
          
        
          
          
          
        
          
          
          
            "theme_profiles": [
              
                "rgb_cycle_speed",
              
            ],
          
        
          
          
          
        
          
          
          
            "discovery_items": [
              
                "score",
              
            ],
          
        
          
          
          
            "streams": [
              
                "viewer_count",
              
            ],
          
        
          
          
          
            "videos": [
              
                "duration_seconds",
              
                "view_count",
              
                "like_count",
              
                "comment_count",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "playlist_items": [
              
                "position",
              
            ],
          
        
          
          
          
            "tip_pages": [
              
                "preset_amount_1",
              
                "preset_amount_2",
              
                "preset_amount_3",
              
                "minimum_amount",
              
            ],
          
        
          
          
          
            "tips": [
              
                "amount",
              
            ],
          
        
          
          
          
        
          
          
          
            "alerts": [
              
                "amount",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "overlay_widgets": [
              
                "x",
              
                "y",
              
                "width",
              
                "height",
              
                "z_index",
              
            ],
          
        
          
          
          
        
          
          
          
            "products": [
              
                "price",
              
                "stock_quantity",
              
            ],
          
        
          
          
          
            "product_variants": [
              
                "price_override",
              
                "stock_quantity",
              
            ],
          
        
          
          
          
            "orders": [
              
                "subtotal",
              
                "shipping_cost",
              
                "tax_total",
              
                "total",
              
            ],
          
        
          
          
          
            "order_items": [
              
                "quantity",
              
                "unit_price",
              
                "line_total",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "demo_wallets": [
              
                "available_balance",
              
                "lifetime_earned",
              
                "lifetime_spent",
              
            ],
          
        
          
          
          
            "wallet_transactions": [
              
                "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;
    }
  }
}