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

          
            "businesses": [
              
                "legal_name",
              
                "trade_name",
              
                "national_id",
              
                "economic_code",
              
                "registration_number",
              
                "phone",
              
                "address",
              
            ],
          
        
          
          

          
            "branches": [
              
                "code",
              
                "name",
              
                "phone",
              
                "address",
              
            ],
          
        
          
          

          
            "fiscal_years": [
              
                "title",
              
            ],
          
        
          
          

          
        
          
          

          
            "app_menus": [
              
                "key",
              
                "title",
              
                "route",
              
                "parent_key",
              
            ],
          
        
          
          

          
            "role_permissions": [
              
                "form_key",
              
                "field_key",
              
            ],
          
        
          
          

          
            "app_settings": [
              
                "default_currency_code",
              
                "numbering_profile_code",
              
            ],
          
        
          
          

          
            "currencies": [
              
                "code",
              
                "name",
              
                "symbol",
              
            ],
          
        
          
          

          
            "currency_rates": [
              
                "source",
              
            ],
          
        
          
          

          
            "numbering_profiles": [
              
                "code",
              
                "title",
              
                "prefix",
              
            ],
          
        
          
          

          
            "widgets": [
              
                "key",
              
                "title",
              
            ],
          
        
          
          

          
            "license_customers": [
              
                "customer_name",
              
                "contact_name",
              
                "email",
              
                "mobile",
              
                "notes",
              
            ],
          
        
          
          

          
            "license_products": [
              
                "product_code",
              
                "product_name",
              
                "version",
              
                "description",
              
            ],
          
        
          
          

          
            "license_keys": [
              
                "license_code",
              
                "hardware_fingerprint",
              
                "server_fingerprint",
              
                "db_fingerprint",
              
                "last_error_message",
              
            ],
          
        
          
          

          
            "license_activations": [
              
                "activated_by",
              
                "client_info",
              
                "activation_token",
              
                "failure_reason",
              
            ],
          
        
          
          

          
            "counterparties": [
              
                "code",
              
                "name",
              
                "national_id",
              
                "economic_code",
              
                "phone",
              
                "address",
              
            ],
          
        
          
          

          
            "cost_centers": [
              
                "code",
              
                "name",
              
            ],
          
        
          
          

          
            "projects": [
              
                "code",
              
                "name",
              
            ],
          
        
          
          

          
            "contracts": [
              
                "contract_number",
              
                "title",
              
            ],
          
        
          
          

          
            "cash_boxes": [
              
                "code",
              
                "name",
              
            ],
          
        
          
          

          
            "banks": [
              
                "code",
              
                "name",
              
                "swift",
              
                "website",
              
            ],
          
        
          
          

          
            "bank_accounts": [
              
                "account_title",
              
                "account_number",
              
                "iban",
              
                "card_number",
              
            ],
          
        
          
          

          
            "letters_of_credit": [
              
                "lc_number",
              
            ],
          
        
          
          

          
            "pos_terminals": [
              
                "terminal_number",
              
                "merchant_number",
              
                "title",
              
            ],
          
        
          
          

          
            "sales_item_groups": [
              
                "code",
              
                "name",
              
                "parent_code",
              
            ],
          
        
          
          

          
            "warehouse_item_groups": [
              
                "code",
              
                "name",
              
                "parent_code",
              
            ],
          
        
          
          

          
            "customer_groups": [
              
                "code",
              
                "name",
              
            ],
          
        
          
          

          
            "analytic_dimensions": [
              
                "code",
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "accounts": [
              
                "code",
              
                "name",
              
                "parent_code",
              
            ],
          
        
          
          

          
            "journal_voucher_types": [
              
                "code",
              
                "name",
              
            ],
          
        
          
          

          
            "journal_vouchers": [
              
                "voucher_number",
              
                "description",
              
            ],
          
        
          
          

          
            "journal_lines": [
              
                "line_description",
              
            ],
          
        
          
          

          
            "approval_workflows": [
              
                "name",
              
            ],
          
        
          
          

          
            "workflow_steps": [
              
                "title",
              
            ],
          
        
          
          

          
            "voucher_approvals": [
              
                "comment",
              
            ],
          
        
          
          

          
            "year_end_operations": [
              
                "notes",
              
            ],
          
        
          
          

          
            "report_definitions": [
              
                "code",
              
                "title",
              
                "path_or_name",
              
                "description",
              
            ],
          
        
          
          

          
            "report_runs": [
              
                "filters_json",
              
                "error_message",
              
            ],
          
        
          
          

          
            "chat_conversations": [
              
                "title",
              
            ],
          
        
          
          

          
        
          
          

          
            "chat_messages": [
              
                "message_text",
              
            ],
          
        
          
          

          
            "form_alarms": [
              
                "form_key",
              
                "message_template",
              
            ],
          
        
          
          

          
            "data_export_jobs": [
              
                "source_connection_name",
              
                "target_connection_name",
              
                "error_message",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "app_menus": [
              
                "sort_order",
              
            ],
          
        
          
          
          
        
          
          
          
            "app_settings": [
              
                "analytic_levels_count",
              
            ],
          
        
          
          
          
            "currencies": [
              
                "minor_unit",
              
            ],
          
        
          
          
          
            "currency_rates": [
              
                "rate",
              
            ],
          
        
          
          
          
            "numbering_profiles": [
              
                "next_number",
              
                "padding",
              
            ],
          
        
          
          
          
            "widgets": [
              
                "sort_order",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "license_keys": [
              
                "allowed_clients",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "contracts": [
              
                "amount",
              
            ],
          
        
          
          
          
            "cash_boxes": [
              
                "opening_balance",
              
            ],
          
        
          
          
          
        
          
          
          
            "bank_accounts": [
              
                "opening_balance",
              
            ],
          
        
          
          
          
            "letters_of_credit": [
              
                "amount",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "analytic_dimensions": [
              
                "level",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "journal_vouchers": [
              
                "total_debit",
              
                "total_credit",
              
            ],
          
        
          
          
          
            "journal_lines": [
              
                "line_no",
              
                "debit",
              
                "credit",
              
                "currency_amount",
              
                "exchange_rate",
              
            ],
          
        
          
          
          
        
          
          
          
            "workflow_steps": [
              
                "step_no",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
      };

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