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

          
            "work_centers": [
              
                "code",
              
                "name",
              
                "location",
              
                "description",
              
            ],
          
        
          
          

          
            "machines": [
              
                "asset_tag",
              
                "name",
              
                "manufacturer",
              
                "model",
              
                "serial_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "maintenance_work_orders": [
              
                "work_order_number",
              
                "problem_description",
              
                "resolution_summary",
              
            ],
          
        
          
          

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

          
            "units_of_measure": [
              
                "code",
              
                "name",
              
            ],
          
        
          
          

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

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

          
            "storage_locations": [
              
                "code",
              
                "name",
              
            ],
          
        
          
          

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

          
        
          
          

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

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

          
            "bom_items": [
              
                "reference_designator",
              
                "notes",
              
            ],
          
        
          
          

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

          
            "routing_steps": [
              
                "step_name",
              
                "work_instructions",
              
            ],
          
        
          
          

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

          
            "production_operations": [
              
                "name",
              
                "notes",
              
            ],
          
        
          
          

          
            "production_material_issues": [
              
                "notes",
              
            ],
          
        
          
          

          
            "production_lots": [
              
                "lot_number",
              
                "notes",
              
            ],
          
        
          
          

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

          
            "qa_checklists": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "qa_checklist_items": [
              
                "check_name",
              
                "instructions",
              
            ],
          
        
          
          

          
            "qa_measurements": [
              
                "text_value",
              
            ],
          
        
          
          

          
            "nonconformances": [
              
                "ncr_number",
              
                "problem_statement",
              
                "containment_action",
              
                "root_cause",
              
                "corrective_action",
              
            ],
          
        
          
          

          
            "documents": [
              
                "document_number",
              
                "title",
              
                "revision",
              
                "summary",
              
            ],
          
        
          
          

          
            "audit_events": [
              
                "entity_name",
              
                "record_reference",
              
                "details",
              
                "ip_address",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
            "maintenance_work_orders": [
              
                "labor_hours",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "materials": [
              
                "standard_cost",
              
                "standard_lead_time_days",
              
                "reorder_point",
              
                "reorder_quantity",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "inventory_balances": [
              
                "quantity_on_hand",
              
                "quantity_reserved",
              
            ],
          
        
          
          
          
            "inventory_transactions": [
              
                "quantity",
              
            ],
          
        
          
          
          
        
          
          
          
            "bom_items": [
              
                "quantity_per",
              
                "scrap_factor",
              
            ],
          
        
          
          
          
        
          
          
          
            "routing_steps": [
              
                "sequence_number",
              
                "setup_time_minutes",
              
                "run_time_minutes",
              
            ],
          
        
          
          
          
            "production_orders": [
              
                "planned_quantity",
              
                "completed_quantity",
              
            ],
          
        
          
          
          
            "production_operations": [
              
                "operation_number",
              
                "good_quantity",
              
                "scrap_quantity",
              
            ],
          
        
          
          
          
            "production_material_issues": [
              
                "quantity_issued",
              
            ],
          
        
          
          
          
            "production_lots": [
              
                "quantity_produced",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "qa_checklist_items": [
              
                "sequence_number",
              
                "lower_limit",
              
                "upper_limit",
              
            ],
          
        
          
          
          
            "qa_measurements": [
              
                "numeric_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;
    }
  }
}