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

          
            "suppliers": [
              
                "supplier_name",
              
                "supplier_code",
              
                "email",
              
                "phone",
              
                "address",
              
            ],
          
        
          
          

          
            "customers": [
              
                "customer_name",
              
                "customer_code",
              
                "email",
              
                "phone",
              
                "address",
              
            ],
          
        
          
          

          
            "uoms": [
              
                "uom_name",
              
                "uom_code",
              
            ],
          
        
          
          

          
            "warehouses": [
              
                "warehouse_name",
              
                "warehouse_code",
              
                "description",
              
            ],
          
        
          
          

          
            "locations": [
              
                "location_name",
              
                "location_code",
              
            ],
          
        
          
          

          
            "items": [
              
                "item_name",
              
                "item_code",
              
                "description",
              
            ],
          
        
          
          

          
            "approved_vendors": [
              
                "supplier_item_code",
              
            ],
          
        
          
          

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

          
            "bom_lines": [
              
                "notes",
              
            ],
          
        
          
          

          
            "routings": [
              
                "routing_name",
              
                "routing_code",
              
                "notes",
              
            ],
          
        
          
          

          
            "work_centers": [
              
                "work_center_name",
              
                "work_center_code",
              
            ],
          
        
          
          

          
            "routing_operations": [
              
                "operation_name",
              
                "work_instructions",
              
            ],
          
        
          
          

          
            "machines": [
              
                "machine_name",
              
                "machine_code",
              
                "manufacturer",
              
                "model",
              
                "serial_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "machine_events": [
              
                "notes",
              
            ],
          
        
          
          

          
            "reason_codes": [
              
                "reason_name",
              
                "reason_code",
              
            ],
          
        
          
          

          
            "work_orders": [
              
                "work_order_number",
              
                "priority",
              
                "notes",
              
            ],
          
        
          
          

          
            "work_order_operations": [
              
                "operation_name",
              
                "notes",
              
            ],
          
        
          
          

          
            "lots": [
              
                "lot_number",
              
                "supplier_lot_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "serials": [
              
                "serial_number",
              
                "notes",
              
            ],
          
        
          
          

          
        
          
          

          
            "inventory_movements": [
              
                "movement_number",
              
                "reference",
              
                "notes",
              
            ],
          
        
          
          

          
            "purchase_orders": [
              
                "purchase_order_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "purchase_order_lines": [
              
                "notes",
              
            ],
          
        
          
          

          
            "inspection_plans": [
              
                "plan_name",
              
                "plan_code",
              
                "instructions",
              
            ],
          
        
          
          

          
            "inspection_characteristics": [
              
                "characteristic_name",
              
                "unit",
              
                "method",
              
            ],
          
        
          
          

          
            "inspections": [
              
                "inspection_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "inspection_results": [
              
                "comments",
              
            ],
          
        
          
          

          
            "nonconformances": [
              
                "ncr_number",
              
                "problem_description",
              
                "containment_actions",
              
            ],
          
        
          
          

          
            "disposition_codes": [
              
                "disposition_name",
              
                "disposition_code",
              
            ],
          
        
          
          

          
            "capa_actions": [
              
                "capa_number",
              
                "root_cause",
              
                "action_plan",
              
                "effectiveness_check",
              
            ],
          
        
          
          

          
            "audit_logs": [
              
                "entity_name",
              
                "record_key",
              
                "details",
              
                "ip_address",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
            "uoms": [
              
                "base_multiplier",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "items": [
              
                "standard_cost",
              
                "shelf_life_days",
              
            ],
          
        
          
          
          
            "approved_vendors": [
              
                "lead_time_days",
              
                "last_price",
              
            ],
          
        
          
          
          
        
          
          
          
            "bom_lines": [
              
                "quantity_per",
              
                "scrap_factor_ppm",
              
                "line_no",
              
            ],
          
        
          
          
          
        
          
          
          
            "work_centers": [
              
                "default_labor_rate",
              
                "default_machine_rate",
              
            ],
          
        
          
          
          
            "routing_operations": [
              
                "operation_no",
              
                "setup_minutes",
              
                "run_minutes_per_unit",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "work_orders": [
              
                "planned_quantity",
              
                "completed_quantity",
              
                "scrap_quantity",
              
            ],
          
        
          
          
          
            "work_order_operations": [
              
                "operation_no",
              
                "good_quantity",
              
                "scrap_quantity",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "inventory_balances": [
              
                "on_hand_quantity",
              
                "allocated_quantity",
              
                "available_quantity",
              
            ],
          
        
          
          
          
            "inventory_movements": [
              
                "quantity",
              
            ],
          
        
          
          
          
        
          
          
          
            "purchase_order_lines": [
              
                "line_no",
              
                "ordered_quantity",
              
                "received_quantity",
              
                "unit_price",
              
            ],
          
        
          
          
          
        
          
          
          
            "inspection_characteristics": [
              
                "sequence_no",
              
                "target_value",
              
                "lower_limit",
              
                "upper_limit",
              
            ],
          
        
          
          
          
        
          
          
          
            "inspection_results": [
              
                "measured_value",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
      };

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