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_code",
              
                "name",
              
                "tax_number",
              
                "email",
              
                "phone",
              
                "address",
              
                "notes",
              
            ],
          
        
          
          

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

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

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

          
            "item_supplier_links": [
              
                "supplier_item_code",
              
                "notes",
              
            ],
          
        
          
          

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

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

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

          
        
          
          

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

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

          
            "bom_lines": [
              
                "remarks",
              
            ],
          
        
          
          

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

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

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

          
            "routing_operations": [
              
                "name",
              
                "work_instructions",
              
            ],
          
        
          
          

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

          
            "production_operations": [
              
                "notes",
              
            ],
          
        
          
          

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

          
            "production_receipts": [
              
                "receipt_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "qa_inspection_plans": [
              
                "plan_code",
              
                "name",
              
                "instructions",
              
            ],
          
        
          
          

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

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

          
            "capa_actions": [
              
                "capa_number",
              
                "root_cause",
              
                "action_plan",
              
            ],
          
        
          
          

          
            "maintenance_work_orders": [
              
                "work_order_number",
              
                "description",
              
                "resolution",
              
            ],
          
        
          
          

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

          
            "purchase_order_lines": [
              
                "notes",
              
            ],
          
        
          
          

          
            "sales_orders": [
              
                "so_number",
              
                "currency",
              
                "notes",
              
            ],
          
        
          
          

          
            "sales_order_lines": [
              
                "notes",
              
            ],
          
        
          
          

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

          
        
          
          

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

          
            "cost_elements": [
              
                "code",
              
                "name",
              
                "notes",
              
            ],
          
        
          
          

          
            "standard_costs": [
              
                "cost_version",
              
                "notes",
              
            ],
          
        
          
          

          
            "production_costs": [
              
                "notes",
              
            ],
          
        
          
          

          
            "price_lists": [
              
                "code",
              
                "name",
              
                "currency",
              
                "notes",
              
            ],
          
        
          
          

          
            "price_list_lines": [
              
                "notes",
              
            ],
          
        
          
          

          
            "documents": [
              
                "document_number",
              
                "title",
              
                "revision",
              
                "summary",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
            "uoms": [
              
                "to_base_factor",
              
            ],
          
        
          
          
          
            "items": [
              
                "default_scrap_rate",
              
                "shelf_life_days",
              
            ],
          
        
          
          
          
            "item_supplier_links": [
              
                "last_purchase_price",
              
                "lead_time_days",
              
                "min_order_qty",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "inventory_balances": [
              
                "quantity_on_hand",
              
                "quantity_allocated",
              
                "quantity_available",
              
            ],
          
        
          
          
          
            "inventory_transactions": [
              
                "quantity",
              
            ],
          
        
          
          
          
            "bom_headers": [
              
                "yield_quantity",
              
            ],
          
        
          
          
          
            "bom_lines": [
              
                "line_number",
              
                "quantity_per",
              
                "scrap_rate",
              
            ],
          
        
          
          
          
            "work_centers": [
              
                "default_setup_minutes",
              
                "default_run_rate_per_hour",
              
            ],
          
        
          
          
          
            "machines": [
              
                "hour_meter",
              
            ],
          
        
          
          
          
        
          
          
          
            "routing_operations": [
              
                "operation_number",
              
                "setup_minutes",
              
                "run_minutes_per_unit",
              
                "queue_minutes",
              
                "move_minutes",
              
            ],
          
        
          
          
          
            "production_orders": [
              
                "planned_quantity",
              
                "completed_quantity",
              
            ],
          
        
          
          
          
            "production_operations": [
              
                "operation_number",
              
                "good_quantity",
              
                "scrap_quantity",
              
            ],
          
        
          
          
          
            "material_issues": [
              
                "quantity_issued",
              
            ],
          
        
          
          
          
            "production_receipts": [
              
                "quantity_received",
              
            ],
          
        
          
          
          
            "qa_inspection_plans": [
              
                "aql_level",
              
            ],
          
        
          
          
          
            "qa_inspections": [
              
                "sample_size",
              
                "defect_count",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "maintenance_work_orders": [
              
                "downtime_minutes",
              
            ],
          
        
          
          
          
            "purchase_orders": [
              
                "subtotal",
              
                "tax_total",
              
                "total",
              
            ],
          
        
          
          
          
            "purchase_order_lines": [
              
                "line_number",
              
                "ordered_quantity",
              
                "unit_price",
              
                "line_total",
              
            ],
          
        
          
          
          
            "sales_orders": [
              
                "subtotal",
              
                "tax_total",
              
                "total",
              
            ],
          
        
          
          
          
            "sales_order_lines": [
              
                "line_number",
              
                "ordered_quantity",
              
                "unit_price",
              
                "discount_percent",
              
                "line_total",
              
            ],
          
        
          
          
          
        
          
          
          
            "shipment_lines": [
              
                "line_number",
              
                "quantity_shipped",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "standard_costs": [
              
                "material_cost",
              
                "labor_cost",
              
                "overhead_cost",
              
                "subcontract_cost",
              
                "total_cost",
              
            ],
          
        
          
          
          
            "production_costs": [
              
                "material_cost",
              
                "labor_cost",
              
                "overhead_cost",
              
                "subcontract_cost",
              
                "total_cost",
              
            ],
          
        
          
          
          
        
          
          
          
            "price_list_lines": [
              
                "unit_price",
              
                "min_quantity",
              
            ],
          
        
          
          
          
        
      };

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