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

          
            "tenants": [
              
                "name",
              
                "subdomain",
              
                "tagline",
              
                "primary_color",
              
                "secondary_color",
              
                "data_retention_policy",
              
            ],
          
        
          
          

          
            "departments": [
              
                "code",
              
                "name",
              
            ],
          
        
          
          

          
            "projects": [
              
                "code",
              
                "name",
              
            ],
          
        
          
          

          
            "budget_lines": [
              
                "code",
              
                "name",
              
            ],
          
        
          
          

          
        
          
          

          
        
          
          

          
            "requisitions": [
              
                "req_number",
              
                "title",
              
                "description",
              
                "return_reason",
              
                "reject_reason",
              
            ],
          
        
          
          

          
            "approval_steps": [
              
                "comment",
              
            ],
          
        
          
          

          
            "procurement_cases": [
              
                "classification_justification",
              
            ],
          
        
          
          

          
            "suppliers": [
              
                "legal_name",
              
                "commercial_name",
              
                "rccm_number",
              
                "tax_id",
              
                "address",
              
                "primary_contact_name",
              
                "primary_contact_email",
              
                "primary_contact_phone",
              
                "bank_name",
              
                "bank_account_number",
              
                "bank_swift",
              
            ],
          
        
          
          

          
            "supplier_categories": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "supplier_diligence_checks": [
              
                "notes",
              
            ],
          
        
          
          

          
            "tender_events": [
              
                "reference",
              
                "title",
              
            ],
          
        
          
          

          
            "supplier_offers": [
              
                "delivery_lead_time",
              
                "warranty_terms",
              
            ],
          
        
          
          

          
            "bid_criteria": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "offer_scores": [
              
                "comment",
              
            ],
          
        
          
          

          
            "awards": [
              
                "award_rationale",
              
            ],
          
        
          
          

          
            "purchase_orders": [
              
                "po_number",
              
            ],
          
        
          
          

          
            "po_lines": [
              
                "item_name",
              
                "description",
              
            ],
          
        
          
          

          
            "goods_receipt_notes": [
              
                "grn_number",
              
                "observations",
              
                "receiver_signature",
              
            ],
          
        
          
          

          
            "grn_lines": [
              
                "remarks",
              
            ],
          
        
          
          

          
            "service_acceptance_notes": [
              
                "san_number",
              
                "deliverable_checklist",
              
                "acceptance_criteria",
              
            ],
          
        
          
          

          
            "discrepancy_cases": [
              
                "description",
              
                "resolution_notes",
              
            ],
          
        
          
          

          
            "archive_items": [
              
                "resource_reference",
              
                "title",
              
                "keywords",
              
            ],
          
        
          
          

          
            "access_logs": [
              
                "resource_reference",
              
                "ip_address",
              
                "user_agent",
              
            ],
          
        
          
          

          
            "notifications": [
              
                "subject",
              
                "message",
              
                "related_reference",
              
            ],
          
        
          
          

          
            "audit_events": [
              
                "event_id",
              
                "resource_reference",
              
                "summary",
              
                "ip_address",
              
                "integrity_hash",
              
                "previous_hash",
              
            ],
          
        
          
          

          
            "export_jobs": [
              
                "parameters_json",
              
            ],
          
        
          
          

          
            "sessions": [
              
                "refresh_token_hash",
              
                "ip_address",
              
                "user_agent",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "workflow_rules": [
              
                "l1_threshold_usd",
              
                "l2_threshold_usd",
              
                "l3_threshold_usd",
              
                "l4_threshold_usd",
              
                "sla_approval_hours",
              
                "sla_procurement_hours",
              
                "sla_reception_hours",
              
            ],
          
        
          
          
          
            "currency_rates": [
              
                "rate",
              
            ],
          
        
          
          
          
            "requisitions": [
              
                "quantity",
              
                "estimated_budget_usd",
              
                "estimated_budget_original",
              
                "fx_rate_to_usd",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "suppliers": [
              
                "performance_score",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "supplier_offers": [
              
                "amount",
              
                "amount_usd",
              
            ],
          
        
          
          
          
            "bid_criteria": [
              
                "weight",
              
            ],
          
        
          
          
          
            "offer_scores": [
              
                "score",
              
            ],
          
        
          
          
          
            "awards": [
              
                "awarded_amount_usd",
              
            ],
          
        
          
          
          
            "purchase_orders": [
              
                "total_amount_usd",
              
                "total_amount_original",
              
            ],
          
        
          
          
          
            "po_lines": [
              
                "quantity_ordered",
              
                "unit_price",
              
                "line_total",
              
            ],
          
        
          
          
          
        
          
          
          
            "grn_lines": [
              
                "quantity_received",
              
                "quantity_rejected",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "archive_items": [
              
                "amount_usd",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
      };

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