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

          
            "memberships": [
              
                "invitation_email",
              
            ],
          
        
          
          

          
            "organization_settings": [
              
                "default_currency_code",
              
                "default_language",
              
                "default_timezone",
              
                "invoice_prefix",
              
                "quote_prefix",
              
                "receipt_prefix",
              
                "invoice_footer_note",
              
            ],
          
        
          
          

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

          
            "contacts": [
              
                "display_name",
              
                "company_name",
              
                "first_name",
              
                "last_name",
              
                "email",
              
                "phone",
              
                "tin",
              
                "vrn",
              
                "billing_address_line1",
              
                "billing_address_line2",
              
                "billing_city",
              
                "billing_state_region",
              
                "billing_postal_code",
              
                "billing_country",
              
                "shipping_address_line1",
              
                "shipping_address_line2",
              
                "shipping_city",
              
                "shipping_state_region",
              
                "shipping_postal_code",
              
                "shipping_country",
              
                "notes",
              
            ],
          
        
          
          

          
            "products": [
              
                "name",
              
                "sku",
              
                "barcode",
              
                "unit_name",
              
                "description",
              
            ],
          
        
          
          

          
            "warehouses": [
              
                "name",
              
                "code",
              
                "address_line1",
              
                "address_line2",
              
                "city",
              
                "state_region",
              
                "country",
              
                "notes",
              
            ],
          
        
          
          

          
        
          
          

          
            "quotes": [
              
                "quote_number",
              
                "currency_code",
              
                "customer_notes",
              
                "terms_and_conditions",
              
            ],
          
        
          
          

          
            "quote_lines": [
              
                "line_description",
              
            ],
          
        
          
          

          
            "invoices": [
              
                "invoice_number",
              
                "currency_code",
              
                "customer_notes",
              
                "terms_and_conditions",
              
            ],
          
        
          
          

          
            "invoice_lines": [
              
                "line_description",
              
            ],
          
        
          
          

          
            "payments": [
              
                "payment_reference",
              
                "currency_code",
              
                "notes",
              
            ],
          
        
          
          

          
            "receipts": [
              
                "receipt_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "expenses": [
              
                "expense_number",
              
                "currency_code",
              
                "memo",
              
            ],
          
        
          
          

          
            "approval_requests": [
              
                "subject",
              
                "reason",
              
                "decision_notes",
              
            ],
          
        
          
          

          
            "projects": [
              
                "name",
              
                "notes",
              
            ],
          
        
          
          

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

          
            "time_entries": [
              
                "notes",
              
            ],
          
        
          
          

          
            "efris_connections": [
              
                "device_number",
              
                "branch_code",
              
                "business_name_on_efris",
              
                "tin_on_efris",
              
                "client_id",
              
                "client_secret",
              
                "api_base_url",
              
                "last_error_message",
              
            ],
          
        
          
          

          
            "efris_submissions": [
              
                "request_payload_json",
              
                "response_payload_json",
              
                "efris_invoice_no",
              
                "efris_receipt_no",
              
                "verification_code",
              
                "qr_code_data",
              
                "error_code",
              
                "error_message",
              
            ],
          
        
          
          

          
            "audit_events": [
              
                "entity_name",
              
                "entity_reference",
              
                "ip_address",
              
                "user_agent",
              
                "details_json",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
            "organization_settings": [
              
                "default_vat_rate",
              
            ],
          
        
          
          
          
            "tax_codes": [
              
                "rate",
              
            ],
          
        
          
          
          
        
          
          
          
            "products": [
              
                "sales_price",
              
                "purchase_cost",
              
                "reorder_level",
              
            ],
          
        
          
          
          
        
          
          
          
            "inventory_items": [
              
                "quantity_on_hand",
              
                "quantity_available",
              
                "average_cost",
              
            ],
          
        
          
          
          
            "quotes": [
              
                "exchange_rate",
              
                "subtotal_amount",
              
                "tax_amount",
              
                "discount_amount",
              
                "total_amount",
              
            ],
          
        
          
          
          
            "quote_lines": [
              
                "quantity",
              
                "unit_price",
              
                "discount_rate",
              
                "line_subtotal",
              
                "tax_amount",
              
                "line_total",
              
            ],
          
        
          
          
          
            "invoices": [
              
                "exchange_rate",
              
                "subtotal_amount",
              
                "tax_amount",
              
                "discount_amount",
              
                "total_amount",
              
                "amount_paid",
              
                "balance_due",
              
            ],
          
        
          
          
          
            "invoice_lines": [
              
                "quantity",
              
                "unit_price",
              
                "discount_rate",
              
                "line_subtotal",
              
                "tax_amount",
              
                "line_total",
              
            ],
          
        
          
          
          
            "payments": [
              
                "amount",
              
                "exchange_rate",
              
            ],
          
        
          
          
          
            "receipts": [
              
                "receipt_amount",
              
            ],
          
        
          
          
          
            "expenses": [
              
                "subtotal_amount",
              
                "tax_amount",
              
                "total_amount",
              
                "exchange_rate",
              
            ],
          
        
          
          
          
        
          
          
          
            "projects": [
              
                "budget_amount",
              
            ],
          
        
          
          
          
            "tasks": [
              
                "priority",
              
            ],
          
        
          
          
          
            "time_entries": [
              
                "hours",
              
                "billable_rate",
              
            ],
          
        
          
          
          
        
          
          
          
            "efris_submissions": [
              
                "attempt_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;
    }
  }
}