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

          
            "customers": [
              
                "customer_code",
              
                "name",
              
                "email",
              
                "phone",
              
                "billing_address",
              
                "shipping_address",
              
                "tax_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "contacts": [
              
                "full_name",
              
                "title_role",
              
                "email",
              
                "phone",
              
                "notes",
              
            ],
          
        
          
          

          
            "leads": [
              
                "lead_code",
              
                "name",
              
                "requirements",
              
            ],
          
        
          
          

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

          
            "quote_line_items": [
              
                "description",
              
            ],
          
        
          
          

          
            "projects": [
              
                "project_number",
              
                "name",
              
                "site_address",
              
                "notes",
              
            ],
          
        
          
          

          
            "project_milestones": [
              
                "name",
              
                "notes",
              
            ],
          
        
          
          

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

          
            "materials": [
              
                "material_code",
              
                "name",
              
                "uom",
              
                "notes",
              
            ],
          
        
          
          

          
            "suppliers": [
              
                "supplier_code",
              
                "name",
              
                "email",
              
                "phone",
              
                "address",
              
                "notes",
              
            ],
          
        
          
          

          
            "inventory_locations": [
              
                "code",
              
                "name",
              
                "address",
              
            ],
          
        
          
          

          
        
          
          

          
            "inventory_transactions": [
              
                "reference",
              
                "notes",
              
            ],
          
        
          
          

          
            "boms": [
              
                "bom_code",
              
                "name",
              
                "notes",
              
            ],
          
        
          
          

          
            "bom_items": [
              
                "description",
              
            ],
          
        
          
          

          
            "purchase_orders": [
              
                "po_number",
              
                "ship_to_address",
              
                "notes",
              
            ],
          
        
          
          

          
            "purchase_order_line_items": [
              
                "description",
              
            ],
          
        
          
          

          
            "goods_receipts": [
              
                "grn_number",
              
                "carrier",
              
                "tracking_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "work_orders": [
              
                "work_order_number",
              
                "instructions",
              
            ],
          
        
          
          

          
            "work_order_materials": [
              
                "notes",
              
            ],
          
        
          
          

          
            "deliveries": [
              
                "delivery_number",
              
                "ship_to_address",
              
                "carrier",
              
                "tracking_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "delivery_items": [
              
                "description",
              
            ],
          
        
          
          

          
            "invoices": [
              
                "invoice_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "invoice_line_items": [
              
                "description",
              
            ],
          
        
          
          

          
            "payments": [
              
                "payment_reference",
              
                "transaction_id",
              
                "notes",
              
            ],
          
        
          
          

          
            "documents": [
              
                "entity_reference",
              
                "name",
              
                "notes",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
            "leads": [
              
                "estimated_value",
              
            ],
          
        
          
          
          
            "quotes": [
              
                "subtotal",
              
                "tax_amount",
              
                "discount_amount",
              
                "total",
              
            ],
          
        
          
          
          
            "quote_line_items": [
              
                "quantity",
              
                "unit_price",
              
                "line_total",
              
                "sort_order",
              
            ],
          
        
          
          
          
            "projects": [
              
                "budget_amount",
              
                "contract_amount",
              
            ],
          
        
          
          
          
        
          
          
          
            "products": [
              
                "unit_price",
              
            ],
          
        
          
          
          
            "materials": [
              
                "standard_cost",
              
                "last_cost",
              
                "sale_price",
              
                "reorder_point",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "inventory_items": [
              
                "on_hand_qty",
              
                "allocated_qty",
              
                "available_qty",
              
                "average_cost",
              
            ],
          
        
          
          
          
            "inventory_transactions": [
              
                "quantity",
              
                "unit_cost",
              
            ],
          
        
          
          
          
            "boms": [
              
                "yield_qty",
              
            ],
          
        
          
          
          
            "bom_items": [
              
                "quantity_per",
              
                "scrap_factor",
              
                "sort_order",
              
            ],
          
        
          
          
          
            "purchase_orders": [
              
                "subtotal",
              
                "tax_amount",
              
                "shipping_amount",
              
                "total",
              
            ],
          
        
          
          
          
            "purchase_order_line_items": [
              
                "quantity_ordered",
              
                "quantity_received",
              
                "unit_cost",
              
                "line_total",
              
                "sort_order",
              
            ],
          
        
          
          
          
        
          
          
          
            "work_orders": [
              
                "planned_qty",
              
                "completed_qty",
              
            ],
          
        
          
          
          
            "work_order_materials": [
              
                "required_qty",
              
                "issued_qty",
              
                "scrap_qty",
              
            ],
          
        
          
          
          
            "deliveries": [
              
                "shipping_cost",
              
            ],
          
        
          
          
          
            "delivery_items": [
              
                "quantity",
              
                "sort_order",
              
            ],
          
        
          
          
          
            "invoices": [
              
                "subtotal",
              
                "tax_amount",
              
                "total",
              
                "balance_due",
              
            ],
          
        
          
          
          
            "invoice_line_items": [
              
                "quantity",
              
                "unit_price",
              
                "line_total",
              
                "sort_order",
              
            ],
          
        
          
          
          
            "payments": [
              
                "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}%` }
                )
              )),
            ],
          };

          

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