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

          
            "user_profiles": [
              
                "cpf",
              
                "spouse_cpf",
              
                "spouse_name",
              
                "mother_name",
              
                "cep",
              
                "street",
              
                "house_number",
              
                "address_complement",
              
                "neighborhood",
              
                "city",
              
                "state_uf",
              
                "phone",
              
                "occupation_text",
              
                "occupation_code",
              
                "cbo_code",
              
                "main_source_cnpj",
              
                "voter_title",
              
                "voter_zone",
              
                "voter_section",
              
                "nit_pis_pasep",
              
                "caepf_number",
              
            ],
          
        
          
          

          
        
          
          

          
            "declarations": [
              
                "previous_receipt_number",
              
                "risk_details_json",
              
                "dec_file_url",
              
            ],
          
        
          
          

          
            "dependents": [
              
                "name",
              
                "cpf",
              
                "relationship_code",
              
            ],
          
        
          
          

          
            "data_sources": [
              
                "institution_name",
              
                "imported_payload_json",
              
            ],
          
        
          
          

          
            "transactions": [
              
                "description",
              
                "ai_category",
              
                "ir_field",
              
                "ir_form",
              
                "review_reason",
              
            ],
          
        
          
          

          
            "documents": [
              
                "file_name",
              
                "storage_url",
              
                "extracted_data_json",
              
                "issuer_name",
              
                "issuer_cnpj",
              
            ],
          
        
          
          

          
            "income_payers_pj": [
              
                "payer_cnpj",
              
                "payer_name",
              
                "informe_document_url",
              
            ],
          
        
          
          

          
            "income_carne_leao_monthly": [
              
                "darf_document_url",
              
            ],
          
        
          
          

          
            "exempt_incomes": [
              
                "source_name",
              
                "source_document",
              
                "competence",
              
            ],
          
        
          
          

          
            "exclusive_incomes": [
              
                "source_name",
              
                "source_document",
              
            ],
          
        
          
          

          
            "assets": [
              
                "group_code",
              
                "item_code",
              
                "description_text",
              
                "country",
              
                "registration_number",
              
                "buyer_document",
              
            ],
          
        
          
          

          
            "debts": [
              
                "debt_code",
              
                "creditor_name",
              
                "creditor_document",
              
                "description_text",
              
            ],
          
        
          
          

          
            "deductible_payments": [
              
                "payment_code",
              
                "beneficiary_name",
              
                "beneficiary_document",
              
                "notes",
              
            ],
          
        
          
          

          
            "investment_positions": [
              
                "ticker",
              
                "asset_name",
              
                "brokerage_name",
              
            ],
          
        
          
          

          
            "trades": [
              
                "ticker",
              
            ],
          
        
          
          

          
            "monthly_capital_gains": [
              
                "darf_code",
              
            ],
          
        
          
          

          
            "risk_analyses": [
              
                "factors_json",
              
                "optimization_suggestions_json",
              
            ],
          
        
          
          

          
            "notifications": [
              
                "title_text",
              
                "message_text",
              
            ],
          
        
          
          

          
        
          
          

          
        
          
          

          
            "audit_logs": [
              
                "entity_name",
              
                "entity_key",
              
                "ip_address",
              
                "user_agent",
              
                "details_json",
              
            ],
          
        
          
          

          
            "consents": [
              
                "version",
              
                "context_json",
              
            ],
          
        
          
          

          
            "job_runs": [
              
                "input_json",
              
                "output_json",
              
                "error_message",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "declarations": [
              
                "base_year",
              
                "tax_calculated",
              
                "tax_withheld",
              
                "refund_amount",
              
                "payable_amount",
              
                "risk_score",
              
            ],
          
        
          
          
          
            "dependents": [
              
                "own_income",
              
            ],
          
        
          
          
          
        
          
          
          
            "transactions": [
              
                "amount",
              
                "confidence_score",
              
            ],
          
        
          
          
          
            "documents": [
              
                "extraction_confidence",
              
                "reference_year",
              
            ],
          
        
          
          
          
            "income_payers_pj": [
              
                "taxable_income",
              
                "official_deductions",
              
                "inss_withheld",
              
                "tax_withheld",
              
                "thirteenth_salary",
              
            ],
          
        
          
          
          
            "income_carne_leao_monthly": [
              
                "year",
              
                "month",
              
                "gross_revenue",
              
                "bookkeeping_deductions",
              
                "taxable_base",
              
                "tax_due",
              
            ],
          
        
          
          
          
            "exempt_incomes": [
              
                "amount",
              
            ],
          
        
          
          
          
            "exclusive_incomes": [
              
                "amount",
              
                "tax_withheld",
              
            ],
          
        
          
          
          
            "assets": [
              
                "value_previous_year",
              
                "value_current_year",
              
                "disposal_value",
              
            ],
          
        
          
          
          
            "debts": [
              
                "balance_previous_year",
              
                "balance_current_year",
              
            ],
          
        
          
          
          
            "deductible_payments": [
              
                "amount_paid",
              
            ],
          
        
          
          
          
            "investment_positions": [
              
                "quantity",
              
                "avg_cost",
              
                "value_previous_year",
              
                "value_current_year",
              
            ],
          
        
          
          
          
            "trades": [
              
                "quantity",
              
                "unit_price",
              
                "fees",
              
            ],
          
        
          
          
          
            "monthly_capital_gains": [
              
                "year",
              
                "month",
              
                "gross_gain",
              
                "gross_loss",
              
                "carryforward_loss",
              
                "net_gain",
              
                "tax_rate",
              
                "tax_due",
              
            ],
          
        
          
          
          
            "risk_analyses": [
              
                "overall_score",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "job_runs": [
              
                "attempt",
              
            ],
          
        
      };

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