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",
              
                "slug",
              
                "timezone",
              
                "default_currency",
              
                "billing_email",
              
            ],
          
        
          
          

          
        
          
          

          
        
          
          

          
            "approval_workflows": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
        
          
          

          
            "approval_requests": [
              
                "object_type",
              
                "object_ref",
              
                "reason",
              
            ],
          
        
          
          

          
            "approval_decisions": [
              
                "comment",
              
            ],
          
        
          
          

          
            "companies": [
              
                "legal_name",
              
                "trade_name",
              
                "tax_id",
              
                "address_line1",
              
                "address_line2",
              
                "city",
              
                "region",
              
                "postal_code",
              
                "country",
              
                "phone",
              
                "website",
              
            ],
          
        
          
          

          
            "customers": [
              
                "customer_code",
              
                "name",
              
                "email",
              
                "phone",
              
                "billing_address",
              
                "shipping_address",
              
                "currency",
              
            ],
          
        
          
          

          
            "suppliers": [
              
                "supplier_code",
              
                "name",
              
                "email",
              
                "phone",
              
                "address",
              
                "currency",
              
            ],
          
        
          
          

          
            "uoms": [
              
                "name",
              
                "symbol",
              
            ],
          
        
          
          

          
            "item_categories": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "items": [
              
                "sku",
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "warehouses": [
              
                "name",
              
                "code",
              
                "address",
              
            ],
          
        
          
          

          
            "locations": [
              
                "name",
              
                "code",
              
            ],
          
        
          
          

          
            "lots": [
              
                "lot_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "serial_numbers": [
              
                "serial_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "inventory_transfers": [
              
                "transfer_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "inventory_transfer_lines": [
              
                "memo",
              
            ],
          
        
          
          

          
            "stock_movements": [
              
                "source_type",
              
                "source_ref",
              
                "notes",
              
            ],
          
        
          
          

          
            "quotations": [
              
                "quote_number",
              
                "currency",
              
                "notes",
              
            ],
          
        
          
          

          
            "quotation_lines": [
              
                "description",
              
            ],
          
        
          
          

          
            "sales_orders": [
              
                "order_number",
              
                "currency",
              
                "shipping_address",
              
                "notes",
              
            ],
          
        
          
          

          
            "sales_order_lines": [
              
                "description",
              
            ],
          
        
          
          

          
        
          
          

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

          
            "invoice_lines": [
              
                "description",
              
            ],
          
        
          
          

          
            "customer_returns": [
              
                "return_number",
              
                "reason",
              
            ],
          
        
          
          

          
            "customer_return_lines": [
              
                "condition_notes",
              
            ],
          
        
          
          

          
            "purchase_orders": [
              
                "po_number",
              
                "currency",
              
                "ship_to_address",
              
                "notes",
              
            ],
          
        
          
          

          
            "purchase_order_lines": [
              
                "description",
              
            ],
          
        
          
          

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

          
            "receipt_lines": [
              
                "memo",
              
            ],
          
        
          
          

          
            "vendor_bills": [
              
                "bill_number",
              
                "currency",
              
                "notes",
              
            ],
          
        
          
          

          
            "vendor_bill_lines": [
              
                "description",
              
                "expense_account_code",
              
            ],
          
        
          
          

          
            "chart_of_accounts": [
              
                "account_code",
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "fiscal_periods": [
              
                "name",
              
            ],
          
        
          
          

          
            "journal_entries": [
              
                "journal_number",
              
                "memo",
              
                "source_type",
              
                "source_ref",
              
            ],
          
        
          
          

          
            "journal_lines": [
              
                "description",
              
                "reference",
              
            ],
          
        
          
          

          
            "payments": [
              
                "payment_number",
              
                "currency",
              
                "reference",
              
            ],
          
        
          
          

          
            "tax_rates": [
              
                "name",
              
                "jurisdiction",
              
            ],
          
        
          
          

          
            "webhooks": [
              
                "name",
              
                "url",
              
                "secret",
              
            ],
          
        
          
          

          
            "webhook_subscriptions": [
              
                "event_type",
              
            ],
          
        
          
          

          
            "webhook_deliveries": [
              
                "event_type",
              
                "request_body",
              
                "response_body",
              
            ],
          
        
          
          

          
            "email_notifications": [
              
                "subject",
              
                "body",
              
                "error_message",
              
                "related_type",
              
                "related_ref",
              
            ],
          
        
          
          

          
            "csv_import_jobs": [
              
                "job_name",
              
                "error_report",
              
            ],
          
        
          
          

          
            "reports": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "dashboards": [
              
                "name",
              
            ],
          
        
          
          

          
            "dashboard_widgets": [
              
                "title",
              
                "config_json",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "approval_steps": [
              
                "step_order",
              
                "min_approvals",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "uoms": [
              
                "base_factor",
              
            ],
          
        
          
          
          
        
          
          
          
            "items": [
              
                "sales_price",
              
                "purchase_cost",
              
                "reorder_point",
              
                "reorder_qty",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "inventory_transfer_lines": [
              
                "quantity",
              
            ],
          
        
          
          
          
            "stock_movements": [
              
                "quantity",
              
            ],
          
        
          
          
          
            "quotations": [
              
                "subtotal",
              
                "tax_total",
              
                "total",
              
            ],
          
        
          
          
          
            "quotation_lines": [
              
                "quantity",
              
                "unit_price",
              
                "discount_amount",
              
                "tax_amount",
              
                "line_total",
              
            ],
          
        
          
          
          
            "sales_orders": [
              
                "subtotal",
              
                "tax_total",
              
                "total",
              
            ],
          
        
          
          
          
            "sales_order_lines": [
              
                "quantity",
              
                "unit_price",
              
                "discount_amount",
              
                "tax_amount",
              
                "line_total",
              
            ],
          
        
          
          
          
            "sales_allocations": [
              
                "quantity",
              
            ],
          
        
          
          
          
            "invoices": [
              
                "subtotal",
              
                "tax_total",
              
                "total",
              
                "balance_due",
              
            ],
          
        
          
          
          
            "invoice_lines": [
              
                "quantity",
              
                "unit_price",
              
                "discount_amount",
              
                "tax_amount",
              
                "line_total",
              
            ],
          
        
          
          
          
            "customer_returns": [
              
                "refund_total",
              
            ],
          
        
          
          
          
            "customer_return_lines": [
              
                "quantity",
              
                "refund_amount",
              
            ],
          
        
          
          
          
            "purchase_orders": [
              
                "subtotal",
              
                "tax_total",
              
                "total",
              
            ],
          
        
          
          
          
            "purchase_order_lines": [
              
                "quantity",
              
                "unit_cost",
              
                "tax_amount",
              
                "line_total",
              
            ],
          
        
          
          
          
        
          
          
          
            "receipt_lines": [
              
                "quantity",
              
                "unit_cost",
              
            ],
          
        
          
          
          
            "vendor_bills": [
              
                "subtotal",
              
                "tax_total",
              
                "total",
              
                "balance_due",
              
            ],
          
        
          
          
          
            "vendor_bill_lines": [
              
                "quantity",
              
                "unit_cost",
              
                "tax_amount",
              
                "line_total",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "journal_lines": [
              
                "debit",
              
                "credit",
              
            ],
          
        
          
          
          
            "payments": [
              
                "amount",
              
            ],
          
        
          
          
          
            "tax_rates": [
              
                "rate",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "webhook_deliveries": [
              
                "attempts",
              
                "http_status",
              
            ],
          
        
          
          
          
        
          
          
          
            "csv_import_jobs": [
              
                "total_rows",
              
                "success_rows",
              
                "error_rows",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "dashboard_widgets": [
              
                "position_x",
              
                "position_y",
              
                "width",
              
                "height",
              
            ],
          
        
      };

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