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

          
            "provinces": [
              
                "name",
              
                "code",
              
            ],
          
        
          
          

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

          
        
          
          

          
            "approval_workflows": [
              
                "name",
              
            ],
          
        
          
          

          
            "approval_steps": [
              
                "name",
              
            ],
          
        
          
          

          
            "approvals": [
              
                "record_type",
              
                "record_key",
              
                "decision_comment",
              
                "rejection_reason",
              
            ],
          
        
          
          

          
            "notifications": [
              
                "title",
              
                "message",
              
                "record_type",
              
                "record_key",
              
            ],
          
        
          
          

          
            "audit_logs": [
              
                "action",
              
                "entity_name",
              
                "record_key",
              
                "summary",
              
                "ip_address",
              
                "user_agent",
              
            ],
          
        
          
          

          
            "fiscal_years": [
              
                "name",
              
            ],
          
        
          
          

          
            "funding_sources": [
              
                "name",
              
                "reference_code",
              
            ],
          
        
          
          

          
            "budget_programs": [
              
                "name",
              
                "code",
              
                "objective",
              
            ],
          
        
          
          

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

          
            "allocations": [
              
                "notes",
              
            ],
          
        
          
          

          
            "budget_reallocations": [
              
                "justification",
              
            ],
          
        
          
          

          
            "procurement_plans": [
              
                "name",
              
            ],
          
        
          
          

          
            "requisitions": [
              
                "requisition_number",
              
                "title",
              
                "scope_of_work",
              
                "rejection_reason",
              
            ],
          
        
          
          

          
            "tenders": [
              
                "tender_number",
              
                "title",
              
                "eligibility_criteria",
              
                "submission_instructions",
              
            ],
          
        
          
          

          
            "vendors": [
              
                "name",
              
                "trade_name",
              
                "registration_number",
              
                "tax_number",
              
                "contact_name",
              
                "contact_email",
              
                "contact_phone",
              
                "address",
              
                "bank_name",
              
                "bank_account_number",
              
                "bank_account_name",
              
                "bank_swift",
              
            ],
          
        
          
          

          
            "vendor_compliance_documents": [
              
                "reference_number",
              
                "review_comment",
              
            ],
          
        
          
          

          
            "bids": [
              
                "bid_reference",
              
                "notes",
              
            ],
          
        
          
          

          
            "bid_evaluations": [
              
                "justification",
              
            ],
          
        
          
          

          
            "awards": [
              
                "award_number",
              
                "award_memo",
              
            ],
          
        
          
          

          
            "programs": [
              
                "name",
              
                "code",
              
                "description",
              
            ],
          
        
          
          

          
            "projects": [
              
                "name",
              
                "project_code",
              
                "implementing_entity",
              
                "objectives",
              
                "reporting_cycle",
              
            ],
          
        
          
          

          
            "project_milestones": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "risks": [
              
                "title",
              
                "description",
              
                "mitigation_plan",
              
            ],
          
        
          
          

          
            "issues": [
              
                "title",
              
                "description",
              
            ],
          
        
          
          

          
            "field_verifications": [
              
                "findings",
              
                "actions_required",
              
            ],
          
        
          
          

          
            "contracts": [
              
                "contract_number",
              
                "title",
              
            ],
          
        
          
          

          
            "contract_amendments": [
              
                "amendment_number",
              
                "description",
              
            ],
          
        
          
          

          
            "contract_milestones": [
              
                "name",
              
                "deliverable_description",
              
            ],
          
        
          
          

          
            "grants": [
              
                "funding_window_name",
              
                "call_reference",
              
                "eligibility_rules",
              
                "notes",
              
            ],
          
        
          
          

          
            "beneficiaries": [
              
                "name",
              
                "registration_number",
              
                "contact_email",
              
                "contact_phone",
              
            ],
          
        
          
          

          
            "grant_applications": [
              
                "application_reference",
              
                "proposal_summary",
              
            ],
          
        
          
          

          
            "grant_evaluations": [
              
                "comments",
              
            ],
          
        
          
          

          
            "grant_tranches": [
              
                "conditions",
              
            ],
          
        
          
          

          
            "expense_categories": [
              
                "name",
              
                "code",
              
                "description",
              
            ],
          
        
          
          

          
            "invoices": [
              
                "invoice_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "payment_requests": [
              
                "request_number",
              
                "justification",
              
            ],
          
        
          
          

          
            "payment_batches": [
              
                "batch_number",
              
            ],
          
        
          
          

          
            "payments": [
              
                "payment_reference",
              
                "failure_reason",
              
            ],
          
        
          
          

          
            "obligations": [
              
                "obligation_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "ledger_entries": [
              
                "entry_reference",
              
                "description",
              
                "record_type",
              
                "record_key",
              
            ],
          
        
          
          

          
            "documents": [
              
                "title",
              
                "description",
              
                "record_type",
              
                "record_key",
              
            ],
          
        
          
          

          
            "compliance_alerts": [
              
                "title",
              
                "details",
              
                "record_type",
              
                "record_key",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "approval_steps": [
              
                "step_order",
              
                "min_amount",
              
                "max_amount",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "funding_sources": [
              
                "total_committed_amount",
              
            ],
          
        
          
          
          
            "budget_programs": [
              
                "approved_amount",
              
            ],
          
        
          
          
          
            "budget_lines": [
              
                "approved_amount",
              
                "committed_amount",
              
                "disbursed_amount",
              
            ],
          
        
          
          
          
            "allocations": [
              
                "amount",
              
            ],
          
        
          
          
          
            "budget_reallocations": [
              
                "amount",
              
            ],
          
        
          
          
          
            "procurement_plans": [
              
                "estimated_total_amount",
              
            ],
          
        
          
          
          
            "requisitions": [
              
                "estimated_amount",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "bids": [
              
                "bid_amount",
              
            ],
          
        
          
          
          
            "bid_evaluations": [
              
                "technical_score",
              
                "financial_score",
              
                "total_score",
              
            ],
          
        
          
          
          
            "awards": [
              
                "award_amount",
              
            ],
          
        
          
          
          
            "programs": [
              
                "budget_amount",
              
            ],
          
        
          
          
          
            "projects": [
              
                "planned_budget",
              
                "completion_percent",
              
            ],
          
        
          
          
          
            "project_milestones": [
              
                "weight_percent",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "contracts": [
              
                "contract_value",
              
                "retention_percent",
              
                "penalty_rate_percent",
              
            ],
          
        
          
          
          
            "contract_amendments": [
              
                "value_change_amount",
              
                "days_extension",
              
            ],
          
        
          
          
          
            "contract_milestones": [
              
                "payment_percent",
              
            ],
          
        
          
          
          
            "grants": [
              
                "total_envelope_amount",
              
            ],
          
        
          
          
          
            "beneficiaries": [
              
                "approved_amount",
              
            ],
          
        
          
          
          
            "grant_applications": [
              
                "requested_amount",
              
            ],
          
        
          
          
          
            "grant_evaluations": [
              
                "score",
              
            ],
          
        
          
          
          
            "grant_tranches": [
              
                "tranche_number",
              
                "amount",
              
            ],
          
        
          
          
          
        
          
          
          
            "invoices": [
              
                "subtotal_amount",
              
                "tax_amount",
              
                "total_amount",
              
            ],
          
        
          
          
          
            "payment_requests": [
              
                "requested_amount",
              
            ],
          
        
          
          
          
            "payment_batches": [
              
                "total_amount",
              
            ],
          
        
          
          
          
            "payments": [
              
                "amount",
              
            ],
          
        
          
          
          
            "obligations": [
              
                "amount",
              
            ],
          
        
          
          
          
            "ledger_entries": [
              
                "debit_amount",
              
                "credit_amount",
              
            ],
          
        
          
          
          
            "documents": [
              
                "version_number",
              
            ],
          
        
          
          
          
        
      };

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