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",
              
                "contact_name",
              
                "email",
              
                "phone",
              
                "address",
              
            ],
          
        
          
          

          
            "customers": [
              
                "customer_name",
              
                "customer_code",
              
                "contact_name",
              
                "email",
              
                "phone",
              
                "billing_address",
              
                "shipping_address",
              
            ],
          
        
          
          

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

          
            "item_categories": [
              
                "category_name",
              
                "category_code",
              
                "description",
              
            ],
          
        
          
          

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

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

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

          
            "lots": [
              
                "lot_code",
              
                "supplier_lot_code",
              
                "certificate_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "inventory_transactions": [
              
                "transaction_number",
              
                "reference",
              
                "reason",
              
            ],
          
        
          
          

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

          
            "bom_lines": [
              
                "line_notes",
              
            ],
          
        
          
          

          
            "routes": [
              
                "route_name",
              
                "route_code",
              
                "description",
              
            ],
          
        
          
          

          
            "operations": [
              
                "operation_name",
              
                "operation_code",
              
                "work_instructions",
              
            ],
          
        
          
          

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

          
            "machine_downtime_events": [
              
                "reason",
              
            ],
          
        
          
          

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

          
            "production_lines": [
              
                "line_name",
              
                "line_code",
              
                "description",
              
            ],
          
        
          
          

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

          
            "work_order_operations": [
              
                "operator_notes",
              
            ],
          
        
          
          

          
            "material_issues": [
              
                "issue_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "material_issue_lines": [
              
                "line_notes",
              
            ],
          
        
          
          

          
            "receipts": [
              
                "receipt_number",
              
                "supplier_document_ref",
              
                "notes",
              
            ],
          
        
          
          

          
            "receipt_lines": [
              
                "line_notes",
              
            ],
          
        
          
          

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

          
            "shipment_lines": [
              
                "line_notes",
              
            ],
          
        
          
          

          
            "qa_inspection_plans": [
              
                "plan_name",
              
                "plan_code",
              
                "notes",
              
            ],
          
        
          
          

          
            "qa_characteristics": [
              
                "characteristic_name",
              
                "characteristic_code",
              
                "test_method",
              
            ],
          
        
          
          

          
            "qa_inspections": [
              
                "inspection_number",
              
                "summary",
              
            ],
          
        
          
          

          
            "qa_results": [
              
                "notes",
              
            ],
          
        
          
          

          
            "nonconformances": [
              
                "nc_number",
              
                "problem_description",
              
                "containment_action",
              
                "root_cause",
              
                "corrective_action",
              
            ],
          
        
          
          

          
            "audit_events": [
              
                "event_name",
              
                "entity_name",
              
                "record_reference",
              
                "details",
              
                "ip_address",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
            "uoms": [
              
                "base_multiplier",
              
            ],
          
        
          
          
          
        
          
          
          
            "items": [
              
                "standard_cost",
              
                "default_purchase_price",
              
                "default_sale_price",
              
                "shelf_life_days",
              
                "reorder_point",
              
                "reorder_qty",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "inventory_transactions": [
              
                "quantity",
              
                "unit_cost",
              
            ],
          
        
          
          
          
        
          
          
          
            "bom_lines": [
              
                "quantity_per",
              
                "scrap_factor",
              
            ],
          
        
          
          
          
        
          
          
          
            "operations": [
              
                "sequence",
              
                "setup_time_minutes",
              
                "run_time_minutes_per_unit",
              
                "labor_time_minutes_per_unit",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "work_orders": [
              
                "planned_quantity",
              
                "completed_quantity",
              
            ],
          
        
          
          
          
            "work_order_operations": [
              
                "sequence",
              
                "good_quantity",
              
                "scrap_quantity",
              
            ],
          
        
          
          
          
        
          
          
          
            "material_issue_lines": [
              
                "quantity",
              
            ],
          
        
          
          
          
        
          
          
          
            "receipt_lines": [
              
                "quantity",
              
                "unit_cost",
              
            ],
          
        
          
          
          
        
          
          
          
            "shipment_lines": [
              
                "quantity",
              
            ],
          
        
          
          
          
            "qa_inspection_plans": [
              
                "sample_size",
              
            ],
          
        
          
          
          
            "qa_characteristics": [
              
                "target_value",
              
                "lower_limit",
              
                "upper_limit",
              
            ],
          
        
          
          
          
            "qa_inspections": [
              
                "sample_size",
              
                "defect_count",
              
            ],
          
        
          
          
          
            "qa_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;
    }
  }
}