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

          
            "projects": [
              
                "name",
              
                "project_code",
              
                "location_name",
              
                "description",
              
            ],
          
        
          
          

          
            "project_phases": [
              
                "gate_notes",
              
            ],
          
        
          
          

          
            "milestones": [
              
                "title",
              
                "details",
              
            ],
          
        
          
          

          
            "ore_bodies": [
              
                "name",
              
                "mineralogy_json",
              
                "notes",
              
            ],
          
        
          
          

          
            "samples": [
              
                "sample_code",
              
                "drillhole_id",
              
                "lithology",
              
                "alteration",
              
                "geomet_domain",
              
                "prep_protocol",
              
            ],
          
        
          
          

          
            "chain_of_custody_events": [
              
                "from_party",
              
                "to_party",
              
                "location",
              
                "shipping_reference",
              
                "notes",
              
            ],
          
        
          
          

          
            "laboratories": [
              
                "name",
              
                "country",
              
                "city",
              
                "contact_email",
              
                "contact_phone",
              
                "notes",
              
            ],
          
        
          
          

          
            "test_type_schemas": [
              
                "test_type",
              
                "display_name_en",
              
                "display_name_fr",
              
                "parameters_schema_json",
              
                "results_schema_json",
              
                "calculation_rules_json",
              
            ],
          
        
          
          

          
            "metallurgical_tests": [
              
                "lab_reference",
              
                "parameters_json",
              
                "results_json",
              
                "qaqc_notes",
              
            ],
          
        
          
          

          
            "test_result_points": [
              
                "parameter_name",
              
                "unit",
              
                "notes",
              
            ],
          
        
          
          

          
            "flowsheets": [
              
                "name",
              
                "description",
              
                "layout_json",
              
            ],
          
        
          
          

          
            "equipment_items": [
              
                "manufacturer",
              
                "model",
              
                "capacity_unit",
              
                "opex_unit",
              
                "vendor_quote_reference",
              
            ],
          
        
          
          

          
            "flowsheet_nodes": [
              
                "node_key",
              
                "name",
              
                "parameters_json",
              
            ],
          
        
          
          

          
            "flowsheet_streams": [
              
                "components_json",
              
            ],
          
        
          
          

          
            "design_criteria_items": [
              
                "parameter",
              
                "unit",
              
                "basis_notes",
              
            ],
          
        
          
          

          
            "economic_models": [
              
                "name",
              
                "assumptions_json",
              
                "sensitivity_json",
              
            ],
          
        
          
          

          
            "capex_items": [
              
                "cost_category",
              
                "description",
              
                "basis_notes",
              
            ],
          
        
          
          

          
            "opex_items": [
              
                "description",
              
                "rate_unit",
              
                "cost_unit",
              
                "basis_notes",
              
            ],
          
        
          
          

          
            "monte_carlo_runs": [
              
                "inputs_json",
              
                "results_json",
              
            ],
          
        
          
          

          
            "documents": [
              
                "title",
              
                "tags",
              
                "description",
              
            ],
          
        
          
          

          
            "entity_links": [
              
                "source_entity_key",
              
                "target_entity_key",
              
                "link_notes",
              
            ],
          
        
          
          

          
            "comments": [
              
                "entity_key",
              
                "body",
              
            ],
          
        
          
          

          
            "tasks": [
              
                "title",
              
                "description",
              
                "entity_key",
              
            ],
          
        
          
          

          
            "notifications": [
              
                "title",
              
                "message",
              
                "entity_key",
              
            ],
          
        
          
          

          
            "audit_logs": [
              
                "entity_type",
              
                "entity_key",
              
                "old_value_json",
              
                "new_value_json",
              
                "change_summary",
              
                "ip_address",
              
                "user_agent",
              
                "session_key",
              
                "checksum",
              
                "previous_checksum",
              
            ],
          
        
          
          

          
            "integrations": [
              
                "name",
              
                "config_json",
              
                "last_error",
              
            ],
          
        
          
          

          
            "offline_sync_batches": [
              
                "payload_json",
              
                "error_details",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
            "projects": [
              
                "latitude",
              
                "longitude",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "ore_bodies": [
              
                "head_grade_au_gpt",
              
                "tonnage_mt",
              
            ],
          
        
          
          
          
            "samples": [
              
                "depth_from_m",
              
                "depth_to_m",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "test_result_points": [
              
                "value",
              
                "confidence_level",
              
            ],
          
        
          
          
          
            "flowsheets": [
              
                "version_number",
              
            ],
          
        
          
          
          
            "equipment_items": [
              
                "capacity",
              
                "power_kw",
              
                "base_capex_usd",
              
                "install_factor",
              
                "opex_per_unit",
              
            ],
          
        
          
          
          
            "flowsheet_nodes": [
              
                "position_x",
              
                "position_y",
              
            ],
          
        
          
          
          
            "flowsheet_streams": [
              
                "mass_flow_tph",
              
                "water_flow_m3h",
              
                "solids_pct",
              
                "au_grade_gpt",
              
                "au_recovery_pct",
              
            ],
          
        
          
          
          
            "design_criteria_items": [
              
                "value",
              
            ],
          
        
          
          
          
            "economic_models": [
              
                "gold_price",
              
                "discount_rate_pct",
              
                "throughput_tpd",
              
                "recovery_pct",
              
                "mine_life_years",
              
                "capex_total",
              
                "opex_per_tonne",
              
                "npv",
              
                "irr_pct",
              
                "payback_years",
              
            ],
          
        
          
          
          
            "capex_items": [
              
                "quantity",
              
                "unit_cost",
              
                "install_factor",
              
                "total_cost",
              
            ],
          
        
          
          
          
            "opex_items": [
              
                "rate",
              
                "unit_cost",
              
                "annual_cost",
              
            ],
          
        
          
          
          
            "monte_carlo_runs": [
              
                "iterations",
              
            ],
          
        
          
          
          
            "documents": [
              
                "version_number",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "offline_sync_batches": [
              
                "items_count",
              
            ],
          
        
      };

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