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

          
            "companies": [
              
                "name",
              
                "legal_name",
              
                "tax_number",
              
                "website",
              
                "phone",
              
                "address_line1",
              
                "address_line2",
              
                "city",
              
                "state_region",
              
                "postal_code",
              
                "country",
              
                "timezone",
              
            ],
          
        
          
          

          
            "plants": [
              
                "name",
              
                "code",
              
                "timezone",
              
                "phone",
              
                "address_line1",
              
                "address_line2",
              
                "city",
              
                "state_region",
              
                "postal_code",
              
                "country",
              
            ],
          
        
          
          

          
            "suppliers": [
              
                "name",
              
                "code",
              
                "contact_name",
              
                "email",
              
                "phone",
              
                "website",
              
                "address_line1",
              
                "address_line2",
              
                "city",
              
                "state_region",
              
                "postal_code",
              
                "country",
              
                "notes",
              
            ],
          
        
          
          

          
            "customers": [
              
                "name",
              
                "code",
              
                "contact_name",
              
                "email",
              
                "phone",
              
                "address_line1",
              
                "address_line2",
              
                "city",
              
                "state_region",
              
                "postal_code",
              
                "country",
              
                "notes",
              
            ],
          
        
          
          

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

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

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

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

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

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

          
            "inventory_balances": [
              
                "uom",
              
            ],
          
        
          
          

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

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

          
            "machine_downtime_events": [
              
                "reason_detail",
              
            ],
          
        
          
          

          
            "work_orders": [
              
                "work_order_number",
              
                "uom",
              
                "customer_po",
              
                "notes",
              
            ],
          
        
          
          

          
            "production_operations": [
              
                "name",
              
                "instructions",
              
            ],
          
        
          
          

          
            "material_issues": [
              
                "uom",
              
                "notes",
              
            ],
          
        
          
          

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

          
            "qa_inspection_plans": [
              
                "name",
              
                "notes",
              
            ],
          
        
          
          

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

          
            "qa_inspections": [
              
                "notes",
              
            ],
          
        
          
          

          
            "qa_results": [
              
                "unit",
              
                "comment",
              
            ],
          
        
          
          

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

          
            "capas": [
              
                "capa_number",
              
                "problem_statement",
              
                "root_cause",
              
                "corrective_action",
              
                "preventive_action",
              
            ],
          
        
          
          

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

          
            "audit_events": [
              
                "entity_reference",
              
                "details",
              
                "ip_address",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "items": [
              
                "shelf_life_days",
              
                "standard_cost",
              
                "standard_price",
              
            ],
          
        
          
          
          
        
          
          
          
            "bom_lines": [
              
                "quantity_per",
              
                "scrap_factor",
              
                "line_number",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "lots": [
              
                "quantity_received",
              
                "quantity_available",
              
            ],
          
        
          
          
          
            "inventory_balances": [
              
                "quantity_on_hand",
              
                "quantity_allocated",
              
                "quantity_available",
              
            ],
          
        
          
          
          
            "inventory_transactions": [
              
                "quantity",
              
            ],
          
        
          
          
          
        
          
          
          
            "machine_downtime_events": [
              
                "duration_minutes",
              
            ],
          
        
          
          
          
            "work_orders": [
              
                "quantity_planned",
              
                "quantity_completed",
              
            ],
          
        
          
          
          
            "production_operations": [
              
                "operation_sequence",
              
                "labor_minutes",
              
                "machine_minutes",
              
            ],
          
        
          
          
          
            "material_issues": [
              
                "quantity_issued",
              
            ],
          
        
          
          
          
            "production_lots": [
              
                "quantity_produced",
              
            ],
          
        
          
          
          
            "qa_inspection_plans": [
              
                "sample_size",
              
            ],
          
        
          
          
          
            "qa_characteristics": [
              
                "lower_spec",
              
                "upper_spec",
              
                "sequence",
              
            ],
          
        
          
          
          
        
          
          
          
            "qa_results": [
              
                "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}%` }
                )
              )),
            ],
          };

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