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

          
            "plants": [
              
                "name",
              
                "code",
              
                "address",
              
                "timezone",
              
            ],
          
        
          
          

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

          
            "machines": [
              
                "name",
              
                "asset_tag",
              
                "serial_number",
              
            ],
          
        
          
          

          
            "machine_events": [
              
                "notes",
              
            ],
          
        
          
          

          
            "uoms": [
              
                "name",
              
                "code",
              
            ],
          
        
          
          

          
            "items": [
              
                "name",
              
                "item_number",
              
                "description",
              
            ],
          
        
          
          

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

          
            "locations": [
              
                "name",
              
                "code",
              
            ],
          
        
          
          

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

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

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

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

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

          
            "routing_operations": [
              
                "name",
              
                "instructions",
              
            ],
          
        
          
          

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

          
            "production_operations": [
              
                "operator_notes",
              
            ],
          
        
          
          

          
            "material_requirements": [
              
                "notes",
              
            ],
          
        
          
          

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

          
            "serial_numbers": [
              
                "serial_number",
              
                "notes",
              
            ],
          
        
          
          

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

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

          
            "inspection_results": [
              
                "characteristic",
              
                "specification",
              
                "notes",
              
            ],
          
        
          
          

          
            "nonconformances": [
              
                "ncr_number",
              
                "description",
              
                "root_cause",
              
                "corrective_action",
              
            ],
          
        
          
          

          
            "quality_holds": [
              
                "hold_number",
              
                "reason",
              
            ],
          
        
          
          

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

          
            "documents": [
              
                "title",
              
                "document_number",
              
                "revision",
              
                "summary",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
            "machines": [
              
                "ideal_cycle_time_seconds",
              
            ],
          
        
          
          
          
            "machine_events": [
              
                "duration_minutes",
              
            ],
          
        
          
          
          
            "uoms": [
              
                "base_multiplier",
              
            ],
          
        
          
          
          
            "items": [
              
                "standard_cost",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "bom_lines": [
              
                "quantity_per",
              
                "scrap_factor_percent",
              
                "line_number",
              
            ],
          
        
          
          
          
        
          
          
          
            "routing_operations": [
              
                "operation_number",
              
                "setup_time_minutes",
              
                "run_time_minutes_per_unit",
              
                "move_time_minutes",
              
                "queue_time_minutes",
              
            ],
          
        
          
          
          
            "production_orders": [
              
                "planned_quantity",
              
                "completed_quantity",
              
                "scrapped_quantity",
              
            ],
          
        
          
          
          
            "production_operations": [
              
                "good_quantity",
              
                "scrap_quantity",
              
            ],
          
        
          
          
          
            "material_requirements": [
              
                "required_quantity",
              
                "issued_quantity",
              
            ],
          
        
          
          
          
            "lots": [
              
                "quantity_on_hand",
              
            ],
          
        
          
          
          
        
          
          
          
            "inventory_transactions": [
              
                "quantity",
              
            ],
          
        
          
          
          
        
          
          
          
            "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;
    }
  }
}