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

          
        
          
          

          
            "tax_rates": [
              
                "name",
              
            ],
          
        
          
          

          
            "payment_terms": [
              
                "name",
              
                "notes",
              
            ],
          
        
          
          

          
            "numbering_sequences": [
              
                "prefix",
              
                "format_hint",
              
            ],
          
        
          
          

          
            "clients": [
              
                "display_name",
              
                "company_name",
              
                "contact_name",
              
                "email",
              
                "phone",
              
                "address",
              
                "city",
              
                "ice",
              
                "if_number",
              
                "rc",
              
                "notes",
              
            ],
          
        
          
          

          
            "suppliers": [
              
                "display_name",
              
                "company_name",
              
                "contact_name",
              
                "email",
              
                "phone",
              
                "address",
              
                "city",
              
                "ice",
              
                "if_number",
              
                "rc",
              
                "bank_name",
              
                "bank_account",
              
                "notes",
              
            ],
          
        
          
          

          
            "product_categories": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "units": [
              
                "name",
              
                "symbol",
              
            ],
          
        
          
          

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

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

          
            "quotes": [
              
                "quote_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "quote_items": [
              
                "designation",
              
                "unit_label",
              
            ],
          
        
          
          

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

          
            "sales_order_items": [
              
                "designation",
              
                "unit_label",
              
            ],
          
        
          
          

          
            "delivery_notes": [
              
                "delivery_note_number",
              
                "carrier_name",
              
                "tracking_reference",
              
                "notes",
              
            ],
          
        
          
          

          
            "delivery_note_items": [
              
                "designation",
              
                "unit_label",
              
            ],
          
        
          
          

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

          
            "invoice_items": [
              
                "designation",
              
                "unit_label",
              
            ],
          
        
          
          

          
            "payments": [
              
                "reference",
              
                "notes",
              
            ],
          
        
          
          

          
            "credit_notes": [
              
                "credit_note_number",
              
                "reason",
              
            ],
          
        
          
          

          
            "credit_note_items": [
              
                "designation",
              
                "unit_label",
              
            ],
          
        
          
          

          
            "purchase_orders": [
              
                "purchase_order_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "purchase_order_items": [
              
                "designation",
              
                "unit_label",
              
            ],
          
        
          
          

          
            "stock_receptions": [
              
                "reception_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "stock_reception_items": [
              
                "batch_code",
              
            ],
          
        
          
          

          
        
          
          

          
            "stock_movements": [
              
                "reference",
              
                "notes",
              
            ],
          
        
          
          

          
            "inventory_counts": [
              
                "inventory_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "inventory_count_items": [
              
                "notes",
              
            ],
          
        
          
          

          
            "import_jobs": [
              
                "log",
              
            ],
          
        
          
          

          
            "audit_logs": [
              
                "entity_name",
              
                "record_reference",
              
                "ip_address",
              
                "user_agent",
              
                "details",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
            "tax_rates": [
              
                "rate_percent",
              
            ],
          
        
          
          
          
            "payment_terms": [
              
                "due_days",
              
            ],
          
        
          
          
          
            "numbering_sequences": [
              
                "next_number",
              
                "padding",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "units": [
              
                "precision",
              
            ],
          
        
          
          
          
            "products": [
              
                "sale_price_ht",
              
                "purchase_price_ht",
              
                "stock_on_hand",
              
                "stock_reserved",
              
                "reorder_level",
              
                "weighted_avg_cost",
              
            ],
          
        
          
          
          
        
          
          
          
            "quotes": [
              
                "subtotal_ht",
              
                "tax_total",
              
                "total_ttc",
              
            ],
          
        
          
          
          
            "quote_items": [
              
                "quantity",
              
                "unit_price_ht",
              
                "discount_percent",
              
                "tax_rate_percent",
              
                "line_total_ht",
              
                "line_tax_total",
              
                "line_total_ttc",
              
            ],
          
        
          
          
          
            "sales_orders": [
              
                "subtotal_ht",
              
                "tax_total",
              
                "total_ttc",
              
            ],
          
        
          
          
          
            "sales_order_items": [
              
                "quantity",
              
                "unit_price_ht",
              
                "discount_percent",
              
                "tax_rate_percent",
              
                "line_total_ht",
              
                "line_tax_total",
              
                "line_total_ttc",
              
            ],
          
        
          
          
          
        
          
          
          
            "delivery_note_items": [
              
                "quantity",
              
            ],
          
        
          
          
          
            "invoices": [
              
                "subtotal_ht",
              
                "tax_total",
              
                "total_ttc",
              
                "amount_paid",
              
            ],
          
        
          
          
          
            "invoice_items": [
              
                "quantity",
              
                "unit_price_ht",
              
                "discount_percent",
              
                "tax_rate_percent",
              
                "line_total_ht",
              
                "line_tax_total",
              
                "line_total_ttc",
              
            ],
          
        
          
          
          
            "payments": [
              
                "amount",
              
            ],
          
        
          
          
          
            "credit_notes": [
              
                "subtotal_ht",
              
                "tax_total",
              
                "total_ttc",
              
            ],
          
        
          
          
          
            "credit_note_items": [
              
                "quantity",
              
                "unit_price_ht",
              
                "tax_rate_percent",
              
                "line_total_ht",
              
                "line_tax_total",
              
                "line_total_ttc",
              
            ],
          
        
          
          
          
            "purchase_orders": [
              
                "subtotal_ht",
              
                "tax_total",
              
                "total_ttc",
              
            ],
          
        
          
          
          
            "purchase_order_items": [
              
                "quantity",
              
                "unit_price_ht",
              
                "tax_rate_percent",
              
                "line_total_ht",
              
                "line_tax_total",
              
                "line_total_ttc",
              
            ],
          
        
          
          
          
        
          
          
          
            "stock_reception_items": [
              
                "quantity_received",
              
                "unit_cost_ht",
              
            ],
          
        
          
          
          
            "stock_reservations": [
              
                "quantity_reserved",
              
            ],
          
        
          
          
          
            "stock_movements": [
              
                "quantity",
              
                "unit_cost_ht",
              
            ],
          
        
          
          
          
        
          
          
          
            "inventory_count_items": [
              
                "quantity_system",
              
                "quantity_counted",
              
                "quantity_diff",
              
            ],
          
        
          
          
          
            "import_jobs": [
              
                "processed_count",
              
                "error_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;
    }
  }
}