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": [
              
                "tenant_name",
              
                "legal_name",
              
                "domain",
              
                "industry",
              
                "default_currency",
              
                "timezone",
              
                "support_email",
              
                "support_phone",
              
                "address",
              
            ],
          
        
          
          

          
            "products": [
              
                "product_name",
              
                "sku",
              
                "barcode",
              
                "brand",
              
                "category",
              
                "unit",
              
                "short_description",
              
                "description",
              
            ],
          
        
          
          

          
            "warehouses": [
              
                "warehouse_name",
              
                "code",
              
                "contact_name",
              
                "contact_phone",
              
                "address",
              
            ],
          
        
          
          

          
            "inventory_items": [
              
                "note",
              
            ],
          
        
          
          

          
            "inventory_movements": [
              
                "reference_type",
              
                "reference_number",
              
                "note",
              
            ],
          
        
          
          

          
            "customers": [
              
                "customer_name",
              
                "email",
              
                "phone_number",
              
                "address",
              
                "city",
              
                "province",
              
                "postal_code",
              
                "notes",
              
            ],
          
        
          
          

          
            "orders": [
              
                "order_number",
              
                "shipping_courier",
              
                "shipping_service",
              
                "tracking_number",
              
                "shipping_address",
              
                "customer_note",
              
                "internal_note",
              
            ],
          
        
          
          

          
            "order_items": [
              
                "item_name",
              
                "sku",
              
            ],
          
        
          
          

          
            "invoices": [
              
                "invoice_number",
              
                "billing_name",
              
                "billing_address",
              
            ],
          
        
          
          

          
            "payments": [
              
                "payment_reference",
              
                "payer_name",
              
                "note",
              
            ],
          
        
          
          

          
            "commission_plans": [
              
                "plan_name",
              
                "notes",
              
            ],
          
        
          
          

          
            "commission_rules": [
              
                "rule_name",
              
            ],
          
        
          
          

          
            "commissions": [
              
                "commission_code",
              
                "notes",
              
            ],
          
        
          
          

          
            "payouts": [
              
                "payout_reference",
              
                "note",
              
            ],
          
        
          
          

          
            "bonus_programs": [
              
                "program_name",
              
                "gift_description",
              
                "terms",
              
            ],
          
        
          
          

          
            "referral_links": [
              
                "link_name",
              
                "code",
              
                "destination_url",
              
            ],
          
        
          
          

          
            "reseller_stores": [
              
                "store_name",
              
                "slug",
              
                "tagline",
              
                "about",
              
                "whatsapp_number",
              
                "instagram_handle",
              
                "tiktok_handle",
              
                "custom_domain",
              
            ],
          
        
          
          

          
            "store_pages": [
              
                "page_title",
              
                "slug",
              
                "content",
              
            ],
          
        
          
          

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

          
            "ai_insights": [
              
                "insight_title",
              
                "insight_summary",
              
                "recommendation",
              
            ],
          
        
          
          

          
            "sales_targets": [
              
                "target_name",
              
                "notes",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
            "products": [
              
                "weight_grams",
              
                "length_cm",
              
                "width_cm",
              
                "height_cm",
              
                "cost_price",
              
                "retail_price",
              
                "reseller_price",
              
                "agent_price",
              
                "distributor_price",
              
                "low_stock_threshold",
              
            ],
          
        
          
          
          
        
          
          
          
            "inventory_items": [
              
                "on_hand_qty",
              
                "reserved_qty",
              
                "available_qty",
              
            ],
          
        
          
          
          
            "inventory_movements": [
              
                "quantity",
              
                "unit_cost",
              
            ],
          
        
          
          
          
        
          
          
          
            "orders": [
              
                "subtotal_amount",
              
                "discount_amount",
              
                "shipping_amount",
              
                "tax_amount",
              
                "total_amount",
              
            ],
          
        
          
          
          
            "order_items": [
              
                "unit_price",
              
                "quantity",
              
                "discount_amount",
              
                "line_total_amount",
              
            ],
          
        
          
          
          
            "invoices": [
              
                "amount_due",
              
                "amount_paid",
              
            ],
          
        
          
          
          
            "payments": [
              
                "amount",
              
            ],
          
        
          
          
          
            "commission_plans": [
              
                "default_rate",
              
                "default_amount",
              
            ],
          
        
          
          
          
            "commission_rules": [
              
                "rate",
              
                "amount",
              
                "min_order_amount",
              
            ],
          
        
          
          
          
            "commissions": [
              
                "base_amount",
              
                "commission_amount",
              
            ],
          
        
          
          
          
            "payouts": [
              
                "gross_amount",
              
                "fee_amount",
              
                "net_amount",
              
            ],
          
        
          
          
          
            "bonus_programs": [
              
                "target_value",
              
                "reward_rate",
              
                "reward_amount",
              
            ],
          
        
          
          
          
            "referral_links": [
              
                "click_count",
              
                "conversion_count",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "sales_targets": [
              
                "target_value",
              
                "achieved_value",
              
            ],
          
        
      };

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