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 ) {
    try {
      if (!searchQuery) {
        throw new ValidationError('iam.errors.searchQueryRequired');
      }
      const tableColumns = {
        
          
          

          
            "users": [
              
                "firstName",
              
                "lastName",
              
                "phoneNumber",
              
                "email",
              
            ],
          
        
          
          
          
          

          
            "brands": [
              
                "name",
              
                "tagline",
              
                "primary_color",
              
                "secondary_color",
              
                "support_email",
              
                "support_phone",
              
            ],
          
        
          
          

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

          
            "products": [
              
                "title",
              
                "slug",
              
                "subtitle",
              
                "description",
              
                "sku",
              
            ],
          
        
          
          

          
            "product_variants": [
              
                "variant_name",
              
                "sku",
              
            ],
          
        
          
          

          
            "paint_colors": [
              
                "name",
              
                "color_code",
              
                "hex_value",
              
                "notes",
              
            ],
          
        
          
          

          
            "product_color_sets": [
              
                "set_name",
              
                "notes",
              
            ],
          
        
          
          

          
            "brush_types": [
              
                "name",
              
                "material",
              
                "description",
              
            ],
          
        
          
          

          
            "product_brush_kits": [
              
                "kit_name",
              
                "notes",
              
            ],
          
        
          
          

          
            "reviews": [
              
                "title",
              
                "content",
              
            ],
          
        
          
          

          
        
          
          

          
        
          
          

          
            "orders": [
              
                "order_number",
              
                "currency",
              
                "customer_note",
              
            ],
          
        
          
          

          
            "order_items": [
              
                "item_title_snapshot",
              
                "variant_snapshot",
              
            ],
          
        
          
          

          
            "addresses": [
              
                "full_name",
              
                "phone",
              
                "line1",
              
                "line2",
              
                "city",
              
                "state_region",
              
                "postal_code",
              
                "country",
              
            ],
          
        
          
          

          
            "shipments": [
              
                "tracking_number",
              
                "tracking_url",
              
            ],
          
        
          
          

          
            "discount_codes": [
              
                "code",
              
                "description",
              
            ],
          
        
          
          

          
            "newsletter_subscriptions": [
              
                "email",
              
                "source",
              
            ],
          
        
          
          

          
            "faq_items": [
              
                "question",
              
                "answer",
              
            ],
          
        
          
          

          
            "content_pages": [
              
                "title",
              
                "slug",
              
                "content",
              
            ],
          
        
          
          

          
            "custom_artwork_requests": [
              
                "instructions",
              
                "ai_model_version",
              
            ],
          
        
          
          

          
            "ai_generation_jobs": [
              
                "provider",
              
                "provider_job_ref",
              
                "error_message",
              
            ],
          
        
          
          

          
            "support_tickets": [
              
                "subject",
              
                "message",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
            "product_categories": [
              
                "sort_order",
              
            ],
          
        
          
          
          
            "products": [
              
                "base_price",
              
                "inventory_quantity",
              
                "rating_average",
              
                "rating_count",
              
            ],
          
        
          
          
          
            "product_variants": [
              
                "price",
              
                "inventory_quantity",
              
            ],
          
        
          
          
          
        
          
          
          
            "product_color_sets": [
              
                "total_colors",
              
            ],
          
        
          
          
          
            "brush_types": [
              
                "size_number",
              
            ],
          
        
          
          
          
            "product_brush_kits": [
              
                "brush_count",
              
            ],
          
        
          
          
          
            "reviews": [
              
                "rating",
              
            ],
          
        
          
          
          
            "carts": [
              
                "subtotal_amount",
              
                "discount_amount",
              
                "shipping_amount",
              
                "tax_amount",
              
                "total_amount",
              
            ],
          
        
          
          
          
            "cart_items": [
              
                "quantity",
              
                "unit_price",
              
                "line_total",
              
            ],
          
        
          
          
          
            "orders": [
              
                "subtotal_amount",
              
                "discount_amount",
              
                "shipping_amount",
              
                "tax_amount",
              
                "total_amount",
              
            ],
          
        
          
          
          
            "order_items": [
              
                "quantity",
              
                "unit_price",
              
                "line_total",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "discount_codes": [
              
                "value_amount",
              
                "minimum_order_amount",
              
                "usage_limit",
              
                "usage_count",
              
            ],
          
        
          
          
          
        
          
          
          
            "faq_items": [
              
                "sort_order",
              
            ],
          
        
          
          
          
        
          
          
          
            "custom_artwork_requests": [
              
                "estimated_color_count",
              
                "estimated_price",
              
            ],
          
        
          
          
          
            "ai_generation_jobs": [
              
                "runtime_seconds",
              
            ],
          
        
          
          
          
        
      };

      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}%` }
                )
              )),
            ],
          };

          

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