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

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

          
            "plants": [
              
                "plant_name",
              
                "plant_code",
              
                "timezone",
              
                "address",
              
            ],
          
        
          
          

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

          
            "storage_locations": [
              
                "location_code",
              
                "location_name",
              
                "notes",
              
            ],
          
        
          
          

          
            "units_of_measure": [
              
                "uom_name",
              
                "uom_code",
              
                "notes",
              
            ],
          
        
          
          

          
            "materials": [
              
                "material_code",
              
                "material_name",
              
                "specification",
              
            ],
          
        
          
          

          
            "material_revisions": [
              
                "revision_code",
              
                "change_summary",
              
            ],
          
        
          
          

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

          
            "bom_lines": [
              
                "reference_designator",
              
                "notes",
              
            ],
          
        
          
          

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

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

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

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

          
            "machine_readings": [
              
                "source",
              
                "notes",
              
            ],
          
        
          
          

          
            "maintenance_work_orders": [
              
                "maintenance_code",
              
                "problem_description",
              
                "work_performed",
              
            ],
          
        
          
          

          
            "shifts": [
              
                "shift_name",
              
                "notes",
              
            ],
          
        
          
          

          
            "production_orders": [
              
                "order_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "work_order_operations": [
              
                "operator_notes",
              
            ],
          
        
          
          

          
            "inventory_lots": [
              
                "lot_number",
              
                "certificate_number",
              
                "notes",
              
            ],
          
        
          
          

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

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

          
            "purchase_order_lines": [
              
                "line_notes",
              
            ],
          
        
          
          

          
            "quality_standards": [
              
                "standard_name",
              
                "standard_code",
              
                "requirements",
              
            ],
          
        
          
          

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

          
            "inspections": [
              
                "inspection_number",
              
                "summary",
              
            ],
          
        
          
          

          
            "nonconformances": [
              
                "ncr_number",
              
                "description",
              
                "containment_action",
              
            ],
          
        
          
          

          
            "capas": [
              
                "capa_number",
              
                "root_cause",
              
                "action_plan",
              
                "effectiveness_notes",
              
            ],
          
        
          
          

          
            "alerts": [
              
                "title_text",
              
                "message",
              
            ],
          
        
          
          

          
            "csv_import_jobs": [
              
                "error_log",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "units_of_measure": [
              
                "base_multiplier",
              
            ],
          
        
          
          
          
            "materials": [
              
                "standard_cost",
              
                "standard_price",
              
                "shelf_life_days",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "bom_lines": [
              
                "quantity_per",
              
                "scrap_factor",
              
            ],
          
        
          
          
          
            "routings": [
              
                "standard_batch_size",
              
            ],
          
        
          
          
          
            "operations": [
              
                "operation_number",
              
                "setup_time_minutes",
              
                "run_time_minutes_per_unit",
              
                "queue_time_minutes",
              
                "move_time_minutes",
              
            ],
          
        
          
          
          
            "work_centers": [
              
                "capacity_units_per_hour",
              
            ],
          
        
          
          
          
            "machines": [
              
                "rated_capacity_per_hour",
              
            ],
          
        
          
          
          
            "machine_readings": [
              
                "metric_value",
              
            ],
          
        
          
          
          
            "maintenance_work_orders": [
              
                "labor_hours",
              
            ],
          
        
          
          
          
        
          
          
          
            "production_orders": [
              
                "planned_quantity",
              
                "completed_quantity",
              
            ],
          
        
          
          
          
            "work_order_operations": [
              
                "good_quantity",
              
                "scrap_quantity",
              
            ],
          
        
          
          
          
            "inventory_lots": [
              
                "quantity_on_hand",
              
            ],
          
        
          
          
          
            "inventory_transactions": [
              
                "quantity",
              
            ],
          
        
          
          
          
        
          
          
          
            "purchase_order_lines": [
              
                "ordered_quantity",
              
                "unit_price",
              
            ],
          
        
          
          
          
        
          
          
          
            "inspection_plans": [
              
                "sample_size",
              
            ],
          
        
          
          
          
            "inspections": [
              
                "sample_size",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "csv_import_jobs": [
              
                "records_processed",
              
                "records_failed",
              
            ],
          
        
      };

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