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

          
            "companies": [
              
                "legal_name",
              
                "trade_name",
              
                "registration_number",
              
                "tax_number",
              
                "currency_code",
              
                "timezone",
              
                "support_email",
              
                "support_phone",
              
            ],
          
        
          
          

          
            "branches": [
              
                "branch_name",
              
                "branch_code",
              
                "phone",
              
                "email",
              
                "address_line",
              
                "city",
              
                "region",
              
            ],
          
        
          
          

          
        
          
          

          
            "audit_logs": [
              
                "action",
              
                "entity_name",
              
                "record_key",
              
                "ip_address",
              
                "details",
              
            ],
          
        
          
          

          
            "product_categories": [
              
                "category_name",
              
                "category_code",
              
                "description",
              
            ],
          
        
          
          

          
            "products": [
              
                "product_name",
              
                "sku",
              
                "barcode",
              
                "unit_of_measure",
              
            ],
          
        
          
          

          
            "price_lists": [
              
                "price_list_name",
              
            ],
          
        
          
          

          
        
          
          

          
            "warehouses": [
              
                "warehouse_name",
              
                "warehouse_code",
              
            ],
          
        
          
          

          
            "inventory_batches": [
              
                "batch_code",
              
            ],
          
        
          
          

          
            "inventory_transactions": [
              
                "reference",
              
                "notes",
              
            ],
          
        
          
          

          
            "stock_adjustments": [
              
                "adjustment_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "stock_adjustment_lines": [
              
                "line_notes",
              
            ],
          
        
          
          

          
            "interbranch_transfers": [
              
                "transfer_number",
              
                "notes",
              
            ],
          
        
          
          

          
        
          
          

          
            "suppliers": [
              
                "supplier_name",
              
                "supplier_code",
              
                "contact_name",
              
                "phone",
              
                "email",
              
                "address",
              
            ],
          
        
          
          

          
            "supplier_products": [
              
                "supplier_sku",
              
            ],
          
        
          
          

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

          
        
          
          

          
            "goods_receipts": [
              
                "grn_number",
              
                "supplier_delivery_note",
              
                "notes",
              
            ],
          
        
          
          

          
            "goods_receipt_lines": [
              
                "batch_code",
              
            ],
          
        
          
          

          
            "supplier_invoices": [
              
                "invoice_number",
              
                "attachment_note",
              
            ],
          
        
          
          

          
            "customers": [
              
                "customer_name",
              
                "phone",
              
                "email",
              
                "customer_code",
              
                "notes",
              
            ],
          
        
          
          

          
            "loyalty_programs": [
              
                "program_name",
              
            ],
          
        
          
          

          
            "pos_registers": [
              
                "register_name",
              
                "register_code",
              
            ],
          
        
          
          

          
            "pos_shifts": [
              
                "shift_number",
              
            ],
          
        
          
          

          
            "sales": [
              
                "receipt_number",
              
                "void_reason",
              
            ],
          
        
          
          

          
        
          
          

          
            "payments": [
              
                "provider",
              
                "reference",
              
            ],
          
        
          
          

          
            "refunds": [
              
                "refund_number",
              
                "reason",
              
            ],
          
        
          
          

          
            "store_checklists": [
              
                "checklist_name",
              
            ],
          
        
          
          

          
            "checklist_items": [
              
                "item_text",
              
            ],
          
        
          
          

          
            "checklist_runs": [
              
                "general_notes",
              
            ],
          
        
          
          

          
            "checklist_run_items": [
              
                "comment",
              
            ],
          
        
          
          

          
            "risk_alerts": [
              
                "title_text",
              
                "description",
              
                "source_reference",
              
            ],
          
        
          
          

          
            "departments": [
              
                "department_name",
              
                "department_code",
              
            ],
          
        
          
          

          
            "employees": [
              
                "employee_number",
              
            ],
          
        
          
          

          
            "work_shifts": [
              
                "shift_name",
              
            ],
          
        
          
          

          
        
          
          

          
            "attendance_records": [
              
                "notes",
              
            ],
          
        
          
          

          
            "payroll_runs": [
              
                "payroll_name",
              
            ],
          
        
          
          

          
        
          
          

          
            "performance_reviews": [
              
                "summary",
              
                "goals",
              
            ],
          
        
          
          

          
            "chart_accounts": [
              
                "account_name",
              
                "account_code",
              
            ],
          
        
          
          

          
            "journal_entries": [
              
                "entry_number",
              
                "reference",
              
                "memo",
              
            ],
          
        
          
          

          
            "journal_lines": [
              
                "line_memo",
              
            ],
          
        
          
          

          
            "expenses": [
              
                "expense_number",
              
                "payee",
              
                "description",
              
            ],
          
        
          
          

          
            "assets": [
              
                "asset_name",
              
                "asset_tag",
              
            ],
          
        
          
          

          
            "marketing_campaigns": [
              
                "campaign_name",
              
                "message_body",
              
            ],
          
        
          
          

          
            "campaign_recipients": [
              
                "provider_reference",
              
            ],
          
        
          
          

          
            "ai_reorder_suggestions": [
              
                "explanation",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "products": [
              
                "tax_rate",
              
                "default_cost",
              
                "default_price",
              
                "minimum_price",
              
                "reorder_level",
              
            ],
          
        
          
          
          
        
          
          
          
            "price_list_items": [
              
                "unit_price",
              
                "min_unit_price",
              
            ],
          
        
          
          
          
        
          
          
          
            "inventory_batches": [
              
                "quantity_on_hand",
              
                "unit_cost",
              
            ],
          
        
          
          
          
            "inventory_transactions": [
              
                "quantity",
              
                "unit_cost",
              
            ],
          
        
          
          
          
        
          
          
          
            "stock_adjustment_lines": [
              
                "quantity_delta",
              
                "unit_cost",
              
            ],
          
        
          
          
          
        
          
          
          
            "transfer_lines": [
              
                "quantity",
              
                "unit_cost",
              
            ],
          
        
          
          
          
            "suppliers": [
              
                "credit_days",
              
                "credit_limit",
              
                "risk_score",
              
            ],
          
        
          
          
          
            "supplier_products": [
              
                "last_price",
              
                "lead_time_days",
              
            ],
          
        
          
          
          
            "purchase_orders": [
              
                "subtotal",
              
                "tax_total",
              
                "total_amount",
              
            ],
          
        
          
          
          
            "purchase_order_lines": [
              
                "quantity_ordered",
              
                "unit_cost",
              
                "line_total",
              
            ],
          
        
          
          
          
            "goods_receipts": [
              
                "total_amount",
              
            ],
          
        
          
          
          
            "goods_receipt_lines": [
              
                "quantity_received",
              
                "unit_cost",
              
                "line_total",
              
            ],
          
        
          
          
          
            "supplier_invoices": [
              
                "subtotal",
              
                "tax_total",
              
                "total_amount",
              
                "amount_paid",
              
            ],
          
        
          
          
          
            "customers": [
              
                "credit_limit",
              
                "credit_days",
              
                "loyalty_points_balance",
              
            ],
          
        
          
          
          
            "loyalty_programs": [
              
                "earn_rate",
              
                "redeem_value",
              
            ],
          
        
          
          
          
        
          
          
          
            "pos_shifts": [
              
                "opening_cash",
              
                "closing_cash_counted",
              
                "expected_cash",
              
                "cash_difference",
              
            ],
          
        
          
          
          
            "sales": [
              
                "subtotal",
              
                "discount_total",
              
                "tax_total",
              
                "total_amount",
              
                "amount_paid",
              
                "change_due",
              
            ],
          
        
          
          
          
            "sale_lines": [
              
                "quantity",
              
                "unit_price",
              
                "discount_amount",
              
                "tax_amount",
              
                "line_total",
              
            ],
          
        
          
          
          
            "payments": [
              
                "amount",
              
            ],
          
        
          
          
          
            "refunds": [
              
                "amount",
              
            ],
          
        
          
          
          
        
          
          
          
            "checklist_items": [
              
                "sort_order",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "employees": [
              
                "base_salary",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "payroll_runs": [
              
                "total_gross",
              
                "total_deductions",
              
                "total_net",
              
            ],
          
        
          
          
          
            "payroll_items": [
              
                "gross_pay",
              
                "deductions",
              
                "net_pay",
              
                "commission_amount",
              
            ],
          
        
          
          
          
            "performance_reviews": [
              
                "score",
              
            ],
          
        
          
          
          
        
          
          
          
            "journal_entries": [
              
                "total_debit",
              
                "total_credit",
              
            ],
          
        
          
          
          
            "journal_lines": [
              
                "amount",
              
            ],
          
        
          
          
          
            "expenses": [
              
                "amount",
              
            ],
          
        
          
          
          
            "assets": [
              
                "purchase_cost",
              
                "useful_life_months",
              
                "salvage_value",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "ai_reorder_suggestions": [
              
                "suggested_quantity",
              
                "confidence",
              
            ],
          
        
      };

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