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 , organizationId, globalAccess) {
    try {
      if (!searchQuery) {
        throw new ValidationError('iam.errors.searchQueryRequired');
      }
      const tableColumns = {
        
          
          

          
            "users": [
              
                "firstName",
              
                "lastName",
              
                "phoneNumber",
              
                "email",
              
            ],
          
        
          
          
          
          

          
            "organizations": [
              
                "name",
              
            ],
          
        
          
          

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

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

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

          
            "materials": [
              
                "name",
              
                "material_number",
              
                "uom",
              
                "revision",
              
                "description",
              
            ],
          
        
          
          

          
            "bom_headers": [
              
                "name",
              
                "bom_number",
              
                "revision",
              
                "notes",
              
            ],
          
        
          
          

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

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

          
            "routing_steps": [
              
                "name",
              
                "work_instructions",
              
            ],
          
        
          
          

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

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

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

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

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

          
            "serials": [
              
                "serial_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "inventory_balances": [
              
                "uom",
              
            ],
          
        
          
          

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

          
            "cycle_counts": [
              
                "count_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "cycle_count_lines": [
              
                "uom",
              
                "notes",
              
            ],
          
        
          
          

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

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

          
            "material_allocations": [
              
                "uom",
              
                "notes",
              
            ],
          
        
          
          

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

          
            "inspection_plans": [
              
                "name",
              
                "plan_number",
              
                "revision",
              
                "instructions",
              
            ],
          
        
          
          

          
            "inspection_characteristics": [
              
                "name",
              
                "unit",
              
            ],
          
        
          
          

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

          
            "inspection_results": [
              
                "notes",
              
            ],
          
        
          
          

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

          
            "dispositions": [
              
                "instructions",
              
            ],
          
        
          
          

          
            "corrective_actions": [
              
                "capa_number",
              
                "root_cause",
              
                "action_plan",
              
                "effectiveness_check",
              
            ],
          
        
          
          

          
            "downtime_events": [
              
                "event_number",
              
                "reason_detail",
              
            ],
          
        
          
          

          
            "machine_readings": [
              
                "notes",
              
            ],
          
        
          
          

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

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

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

          
            "shipment_lines": [
              
                "uom",
              
                "notes",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "bom_lines": [
              
                "quantity_per",
              
                "scrap_factor",
              
                "line_number",
              
            ],
          
        
          
          
          
        
          
          
          
            "routing_steps": [
              
                "step_number",
              
                "setup_time_minutes",
              
                "run_time_minutes",
              
                "labor_minutes",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "lots": [
              
                "quantity_received",
              
            ],
          
        
          
          
          
        
          
          
          
            "inventory_balances": [
              
                "on_hand_qty",
              
                "allocated_qty",
              
                "available_qty",
              
            ],
          
        
          
          
          
            "inventory_transactions": [
              
                "quantity",
              
            ],
          
        
          
          
          
        
          
          
          
            "cycle_count_lines": [
              
                "system_qty",
              
                "counted_qty",
              
                "variance_qty",
              
            ],
          
        
          
          
          
            "production_orders": [
              
                "planned_qty",
              
                "completed_qty",
              
                "scrapped_qty",
              
            ],
          
        
          
          
          
            "production_operations": [
              
                "operation_number",
              
                "good_qty",
              
                "scrap_qty",
              
            ],
          
        
          
          
          
            "material_allocations": [
              
                "required_qty",
              
                "issued_qty",
              
            ],
          
        
          
          
          
            "production_lots": [
              
                "quantity_produced",
              
            ],
          
        
          
          
          
        
          
          
          
            "inspection_characteristics": [
              
                "sequence",
              
                "target_value",
              
                "lower_spec_limit",
              
                "upper_spec_limit",
              
            ],
          
        
          
          
          
        
          
          
          
            "inspection_results": [
              
                "measured_value",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "machine_readings": [
              
                "run_minutes",
              
                "down_minutes",
              
                "good_count",
              
                "scrap_count",
              
                "cycle_time_seconds",
              
                "energy_kwh",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "shipment_lines": [
              
                "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}%` }
                )
              )),
            ],
          };

           
          if (!globalAccess && tableName !== 'organizations' && organizationId) {
            whereCondition.organizationId = organizationId;
          }
          

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