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

          
            "api_providers": [
              
                "name",
              
                "base_url",
              
                "notes",
              
            ],
          
        
          
          

          
            "market_symbols": [
              
                "symbol",
              
                "name",
              
                "exchange",
              
                "currency",
              
                "country",
              
                "sector",
              
                "industry",
              
            ],
          
        
          
          

          
            "symbol_fundamentals": [
              
                "source",
              
            ],
          
        
          
          

          
            "price_quotes": [
              
                "source",
              
            ],
          
        
          
          

          
            "technical_indicators": [
              
                "source",
              
            ],
          
        
          
          

          
            "analyst_ratings": [
              
                "firm_name",
              
                "summary",
              
                "source_url",
              
            ],
          
        
          
          

          
            "earnings_reports": [
              
                "notes",
              
            ],
          
        
          
          

          
            "news_articles": [
              
                "title",
              
                "publisher",
              
                "url",
              
                "summary",
              
                "content",
              
                "source",
              
            ],
          
        
          
          

          
        
          
          

          
            "article_bookmarks": [
              
                "note",
              
            ],
          
        
          
          

          
            "watchlists": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "watchlist_items": [
              
                "note",
              
            ],
          
        
          
          

          
            "paper_accounts": [
              
                "name",
              
            ],
          
        
          
          

          
            "paper_orders": [
              
                "rejection_reason",
              
            ],
          
        
          
          

          
            "paper_trades": [
              
                "venue",
              
            ],
          
        
          
          

          
        
          
          

          
        
          
          

          
            "screener_filters": [
              
                "name",
              
                "sector",
              
            ],
          
        
          
          

          
            "screener_runs": [
              
                "error_message",
              
            ],
          
        
          
          

          
            "screener_results": [
              
                "sector",
              
            ],
          
        
          
          

          
            "ai_chat_sessions": [
              
                "title",
              
            ],
          
        
          
          

          
            "ai_messages": [
              
                "content",
              
            ],
          
        
          
          

          
            "learning_modules": [
              
                "title",
              
                "summary",
              
                "content",
              
            ],
          
        
          
          

          
            "user_tooltips": [
              
                "tooltip_key",
              
            ],
          
        
          
          

          
            "ir_companies": [
              
                "name",
              
                "website",
              
                "description",
              
                "hq_location",
              
            ],
          
        
          
          

          
            "ir_management_members": [
              
                "full_name",
              
                "title",
              
                "bio",
              
            ],
          
        
          
          

          
            "ir_filings": [
              
                "title",
              
                "sec_url",
              
                "summary",
              
            ],
          
        
          
          

          
        
          
          

          
            "ir_announcements": [
              
                "title",
              
                "body",
              
                "source_url",
              
            ],
          
        
          
          

          
            "ir_financial_statement_summaries": [
              
                "notes",
              
            ],
          
        
          
          

          
            "audit_events": [
              
                "entity_name",
              
                "entity_reference",
              
                "metadata_json",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
            "symbol_fundamentals": [
              
                "pe_ratio",
              
                "eps",
              
                "market_cap",
              
                "revenue",
              
                "dividend_yield",
              
                "beta",
              
                "shares_outstanding",
              
            ],
          
        
          
          
          
            "price_quotes": [
              
                "price",
              
                "open",
              
                "high",
              
                "low",
              
                "previous_close",
              
                "change_amount",
              
                "change_percent",
              
                "volume",
              
            ],
          
        
          
          
          
            "technical_indicators": [
              
                "period",
              
                "value",
              
                "signal",
              
                "histogram",
              
                "upper_band",
              
                "middle_band",
              
                "lower_band",
              
            ],
          
        
          
          
          
            "analyst_ratings": [
              
                "price_target",
              
            ],
          
        
          
          
          
            "earnings_reports": [
              
                "reported_eps",
              
                "estimated_eps",
              
                "surprise",
              
                "surprise_percent",
              
                "reported_revenue",
              
                "estimated_revenue",
              
            ],
          
        
          
          
          
        
          
          
          
            "news_article_symbols": [
              
                "sentiment_score",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "watchlist_items": [
              
                "alert_above_price",
              
                "alert_below_price",
              
            ],
          
        
          
          
          
            "paper_accounts": [
              
                "starting_cash",
              
                "cash_balance",
              
                "buying_power",
              
            ],
          
        
          
          
          
            "paper_orders": [
              
                "quantity",
              
                "limit_price",
              
                "stop_price",
              
                "filled_quantity",
              
                "average_fill_price",
              
            ],
          
        
          
          
          
            "paper_trades": [
              
                "quantity",
              
                "price",
              
                "fees",
              
            ],
          
        
          
          
          
            "paper_positions": [
              
                "quantity",
              
                "average_cost",
              
                "market_value",
              
                "unrealized_pl",
              
                "realized_pl",
              
                "day_pl",
              
            ],
          
        
          
          
          
            "portfolio_snapshots": [
              
                "total_value",
              
                "cash_value",
              
                "positions_value",
              
                "day_pl",
              
                "all_time_pl",
              
                "day_pl_percent",
              
            ],
          
        
          
          
          
            "screener_filters": [
              
                "market_cap_min",
              
                "market_cap_max",
              
                "pe_min",
              
                "pe_max",
              
                "price_min",
              
                "price_max",
              
                "volume_min",
              
                "performance_52w_min",
              
                "performance_52w_max",
              
            ],
          
        
          
          
          
            "screener_runs": [
              
                "result_count",
              
            ],
          
        
          
          
          
            "screener_results": [
              
                "last_price",
              
                "market_cap",
              
                "pe_ratio",
              
                "volume",
              
                "performance_52w",
              
            ],
          
        
          
          
          
        
          
          
          
            "ai_messages": [
              
                "confidence",
              
            ],
          
        
          
          
          
            "learning_modules": [
              
                "estimated_minutes",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "ir_management_members": [
              
                "display_order",
              
            ],
          
        
          
          
          
        
          
          
          
            "ir_dividends": [
              
                "amount",
              
            ],
          
        
          
          
          
        
          
          
          
            "ir_financial_statement_summaries": [
              
                "total_revenue",
              
                "net_income",
              
                "total_assets",
              
                "total_liabilities",
              
                "free_cash_flow",
              
            ],
          
        
          
          
          
        
      };

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