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

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

          
            "maintenance_work_orders": [
              
                "work_order_number",
              
                "issue_description",
              
                "work_performed",
              
            ],
          
        
          
          

          
            "downtime_events": [
              
                "notes",
              
            ],
          
        
          
          

          
            "uoms": [
              
                "name",
              
                "symbol",
              
            ],
          
        
          
          

          
            "item_categories": [
              
                "name",
              
                "code",
              
            ],
          
        
          
          

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

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

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

          
            "inventory_lots": [
              
                "lot_number",
              
                "supplier_lot",
              
            ],
          
        
          
          

          
        
          
          

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

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

          
            "customers": [
              
                "name",
              
                "customer_code",
              
                "email",
              
                "phone",
              
                "address",
              
                "tax_number",
              
            ],
          
        
          
          

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

          
            "purchase_order_lines": [
              
                "description",
              
            ],
          
        
          
          

          
            "receipts": [
              
                "receipt_number",
              
                "carrier_reference",
              
            ],
          
        
          
          

          
            "receipt_lines": [
              
                "lot_number",
              
            ],
          
        
          
          

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

          
            "bom_lines": [
              
                "notes",
              
            ],
          
        
          
          

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

          
            "routing_operations": [
              
                "operation_name",
              
                "instructions",
              
            ],
          
        
          
          

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

          
            "production_operations": [
              
                "operation_name",
              
                "operator_notes",
              
            ],
          
        
          
          

          
            "production_materials": [
              
                "notes",
              
            ],
          
        
          
          

          
            "production_outputs": [
              
                "lot_number",
              
            ],
          
        
          
          

          
            "qa_plans": [
              
                "name",
              
                "instructions",
              
            ],
          
        
          
          

          
            "qa_characteristics": [
              
                "name",
              
                "unit",
              
                "method",
              
            ],
          
        
          
          

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

          
            "qa_results": [
              
                "text_value",
              
                "notes",
              
            ],
          
        
          
          

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

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

          
            "audit_logs": [
              
                "entity_name",
              
                "record_key",
              
                "ip_address",
              
                "user_agent",
              
                "details",
              
            ],
          
        
          
          

          
            "gl_accounts": [
              
                "account_code",
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "journal_entries": [
              
                "journal_number",
              
                "memo",
              
            ],
          
        
          
          

          
            "journal_lines": [
              
                "description",
              
            ],
          
        
          
          

          
            "cost_centers": [
              
                "name",
              
                "code",
              
            ],
          
        
          
          

          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "maintenance_work_orders": [
              
                "labor_hours",
              
                "parts_cost",
              
            ],
          
        
          
          
          
        
          
          
          
            "uoms": [
              
                "base_factor",
              
            ],
          
        
          
          
          
        
          
          
          
            "items": [
              
                "standard_cost",
              
                "standard_price",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "inventory_balances": [
              
                "quantity_on_hand",
              
                "quantity_allocated",
              
                "quantity_available",
              
            ],
          
        
          
          
          
            "inventory_transactions": [
              
                "quantity",
              
                "unit_cost",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "purchase_orders": [
              
                "total_amount",
              
            ],
          
        
          
          
          
            "purchase_order_lines": [
              
                "quantity_ordered",
              
                "unit_price",
              
            ],
          
        
          
          
          
        
          
          
          
            "receipt_lines": [
              
                "quantity_received",
              
            ],
          
        
          
          
          
        
          
          
          
            "bom_lines": [
              
                "quantity_per",
              
                "scrap_factor",
              
            ],
          
        
          
          
          
        
          
          
          
            "routing_operations": [
              
                "operation_sequence",
              
                "setup_time_minutes",
              
                "run_time_minutes_per_unit",
              
                "queue_time_minutes",
              
                "move_time_minutes",
              
            ],
          
        
          
          
          
            "production_orders": [
              
                "quantity_planned",
              
                "quantity_completed",
              
            ],
          
        
          
          
          
            "production_operations": [
              
                "operation_sequence",
              
                "good_quantity",
              
                "scrap_quantity",
              
            ],
          
        
          
          
          
            "production_materials": [
              
                "quantity_required",
              
                "quantity_issued",
              
            ],
          
        
          
          
          
            "production_outputs": [
              
                "quantity_produced",
              
            ],
          
        
          
          
          
        
          
          
          
            "qa_characteristics": [
              
                "target_value",
              
                "lower_limit",
              
                "upper_limit",
              
            ],
          
        
          
          
          
        
          
          
          
            "qa_results": [
              
                "numeric_value",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "journal_entries": [
              
                "total_debit",
              
                "total_credit",
              
            ],
          
        
          
          
          
            "journal_lines": [
              
                "debit_amount",
              
                "credit_amount",
              
            ],
          
        
          
          
          
        
          
          
          
            "item_costs": [
              
                "material_cost",
              
                "labor_cost",
              
                "overhead_cost",
              
                "standard_cost",
              
            ],
          
        
      };

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