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

          
            "pages": [
              
                "title",
              
                "slug",
              
                "meta_title",
              
                "meta_description",
              
                "meta_keywords",
              
                "hero_heading",
              
                "hero_subheading",
              
                "content",
              
            ],
          
        
          
          

          
            "cta_buttons": [
              
                "label",
              
                "url",
              
            ],
          
        
          
          

          
            "feature_highlights": [
              
                "title",
              
                "summary",
              
                "icon_name",
              
            ],
          
        
          
          

          
            "galleries": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "gallery_items": [
              
                "caption",
              
                "alt_text",
              
            ],
          
        
          
          

          
            "coffee_regions": [
              
                "region_name",
              
                "slug",
              
                "flavor_profile",
              
                "rainfall_note",
              
                "story",
              
            ],
          
        
          
          

          
            "coffee_lots": [
              
                "lot_code",
              
                "tasting_notes",
              
                "certifications",
              
            ],
          
        
          
          

          
            "quality_processes": [
              
                "headline",
              
                "description",
              
                "profile_highlight",
              
            ],
          
        
          
          

          
            "process_steps": [
              
                "step_title",
              
                "step_description",
              
                "icon_name",
              
            ],
          
        
          
          

          
            "quality_metrics": [
              
                "metric_name",
              
                "target_range",
              
                "details",
              
            ],
          
        
          
          

          
            "export_service_items": [
              
                "service_title",
              
                "service_description",
              
                "icon_name",
              
            ],
          
        
          
          

          
            "sustainability_initiatives": [
              
                "initiative_title",
              
                "description",
              
            ],
          
        
          
          

          
            "testimonials": [
              
                "client_name",
              
                "company_name",
              
                "country",
              
                "quote",
              
            ],
          
        
          
          

          
            "newsletter_subscribers": [
              
                "email",
              
                "full_name",
              
                "company_name",
              
                "country",
              
            ],
          
        
          
          

          
            "inquiries": [
              
                "full_name",
              
                "email",
              
                "phone",
              
                "company_name",
              
                "country",
              
                "message",
              
            ],
          
        
          
          

          
            "contact_locations": [
              
                "location_name",
              
                "address",
              
                "city",
              
                "region",
              
                "country",
              
                "email",
              
                "phone_primary",
              
                "phone_secondary",
              
            ],
          
        
          
          

          
            "site_settings": [
              
                "brand_name",
              
                "footer_tagline",
              
                "primary_color_hex",
              
                "secondary_color_hex",
              
                "accent_color_hex",
              
                "default_meta_title",
              
                "default_meta_description",
              
                "default_meta_keywords",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
            "cta_buttons": [
              
                "sort_order",
              
            ],
          
        
          
          
          
            "feature_highlights": [
              
                "sort_order",
              
            ],
          
        
          
          
          
        
          
          
          
            "gallery_items": [
              
                "sort_order",
              
            ],
          
        
          
          
          
            "coffee_regions": [
              
                "altitude_min_masl",
              
                "altitude_max_masl",
              
                "sort_order",
              
            ],
          
        
          
          
          
            "coffee_lots": [
              
                "crop_year",
              
                "moisture_percent",
              
                "scaa_score",
              
                "available_quantity_kg",
              
            ],
          
        
          
          
          
        
          
          
          
            "process_steps": [
              
                "step_number",
              
            ],
          
        
          
          
          
            "quality_metrics": [
              
                "sort_order",
              
            ],
          
        
          
          
          
            "export_service_items": [
              
                "sort_order",
              
            ],
          
        
          
          
          
            "sustainability_initiatives": [
              
                "sort_order",
              
            ],
          
        
          
          
          
            "testimonials": [
              
                "rating",
              
            ],
          
        
          
          
          
        
          
          
          
            "inquiries": [
              
                "target_volume_kg",
              
            ],
          
        
          
          
          
            "contact_locations": [
              
                "latitude",
              
                "longitude",
              
            ],
          
        
          
          
          
        
      };

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