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

          
            "accounts": [
              
                "account_name",
              
                "account_number",
              
                "tax_exempt_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "locations": [
              
                "location_name",
              
                "address_line_1",
              
                "address_line_2",
              
                "city",
              
                "state",
              
                "postal_code",
              
                "country",
              
                "delivery_instructions",
              
            ],
          
        
          
          

          
            "contacts": [
              
                "contact_name",
              
                "email",
              
                "phone",
              
                "role_title",
              
            ],
          
        
          
          

          
            "product_categories": [
              
                "category_name",
              
                "category_description",
              
            ],
          
        
          
          

          
            "products": [
              
                "sku",
              
                "product_name",
              
                "brand",
              
                "short_description",
              
                "long_description",
              
                "pack_size",
              
                "uom",
              
                "allergens",
              
                "certifications",
              
            ],
          
        
          
          

          
            "inventory_items": [
              
                "warehouse_name",
              
            ],
          
        
          
          

          
            "price_lists": [
              
                "price_list_name",
              
                "notes",
              
            ],
          
        
          
          

          
        
          
          

          
        
          
          

          
            "carts": [
              
                "po_number",
              
                "buyer_notes",
              
            ],
          
        
          
          

          
            "cart_items": [
              
                "line_notes",
              
            ],
          
        
          
          

          
            "orders": [
              
                "order_number",
              
                "po_number",
              
                "buyer_notes",
              
                "internal_notes",
              
            ],
          
        
          
          

          
            "order_items": [
              
                "line_notes",
              
            ],
          
        
          
          

          
            "shipments": [
              
                "shipment_number",
              
                "tracking_number",
              
            ],
          
        
          
          

          
            "quotes": [
              
                "quote_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "quote_items": [
              
                "line_notes",
              
            ],
          
        
          
          

          
            "sample_requests": [
              
                "sample_request_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "saved_lists": [
              
                "list_name",
              
                "notes",
              
            ],
          
        
          
          

          
            "saved_list_items": [
              
                "notes",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
            "accounts": [
              
                "credit_limit",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "products": [
              
                "units_per_case",
              
                "unit_weight_lbs",
              
                "case_weight_lbs",
              
                "moq_cases",
              
            ],
          
        
          
          
          
            "inventory_items": [
              
                "on_hand_cases",
              
                "allocated_cases",
              
                "available_cases",
              
            ],
          
        
          
          
          
        
          
          
          
            "price_list_items": [
              
                "case_price",
              
                "unit_price",
              
                "min_case_qty",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "cart_items": [
              
                "quantity_cases",
              
                "unit_price",
              
                "case_price",
              
            ],
          
        
          
          
          
            "orders": [
              
                "subtotal",
              
                "tax_total",
              
                "shipping_total",
              
                "order_total",
              
            ],
          
        
          
          
          
            "order_items": [
              
                "quantity_cases",
              
                "case_price",
              
                "line_total",
              
            ],
          
        
          
          
          
        
          
          
          
            "quotes": [
              
                "quote_total",
              
            ],
          
        
          
          
          
            "quote_items": [
              
                "quantity_cases",
              
                "case_price",
              
                "line_total",
              
            ],
          
        
          
          
          
            "sample_requests": [
              
                "sample_quantity",
              
            ],
          
        
          
          
          
        
          
          
          
            "saved_list_items": [
              
                "default_quantity_cases",
              
            ],
          
        
      };

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