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

          
            "public_profiles": [
              
                "display_name",
              
                "headline",
              
                "bio",
              
                "location",
              
                "public_slug",
              
            ],
          
        
          
          

          
            "private_profiles": [
              
                "goals_summary",
              
                "focus_area",
              
                "time_commitment",
              
                "constraints_notes",
              
                "ai_profile_draft",
              
                "vision_statement",
              
            ],
          
        
          
          

          
            "membership_plans": [
              
                "plan_name",
              
                "plan_description",
              
                "currency",
              
                "stripe_product_ref",
              
                "stripe_price_ref",
              
            ],
          
        
          
          

          
            "memberships": [
              
                "stripe_customer_ref",
              
                "stripe_subscription_ref",
              
            ],
          
        
          
          

          
            "stripe_events": [
              
                "event_ref",
              
                "processing_notes",
              
            ],
          
        
          
          

          
            "courses": [
              
                "course_title",
              
                "course_description",
              
            ],
          
        
          
          

          
            "lessons": [
              
                "lesson_title",
              
                "lesson_summary",
              
                "content_body",
              
            ],
          
        
          
          

          
        
          
          

          
            "lesson_progress": [
              
                "last_checkpoint",
              
            ],
          
        
          
          

          
            "artifacts": [
              
                "title",
              
                "content_text",
              
            ],
          
        
          
          

          
            "trophies": [
              
                "trophy_name",
              
                "trophy_description",
              
                "icon_key",
              
            ],
          
        
          
          

          
            "user_trophies": [
              
                "award_reason",
              
            ],
          
        
          
          

          
            "ai_gateways": [
              
                "gateway_name",
              
                "base_url",
              
                "default_model",
              
            ],
          
        
          
          

          
            "usage_limit_policies": [
              
                "policy_name",
              
            ],
          
        
          
          

          
            "ai_tasks": [
              
                "task_name",
              
                "system_prompt_template",
              
            ],
          
        
          
          

          
            "ai_requests": [
              
                "model_used",
              
                "error_message",
              
            ],
          
        
          
          

          
            "ai_outputs": [
              
                "output_title",
              
                "output_text",
              
            ],
          
        
          
          

          
            "coaching_sessions": [
              
                "topic",
              
                "private_notes",
              
            ],
          
        
          
          

          
            "messages": [
              
                "content",
              
            ],
          
        
          
          

          
            "resume_documents": [
              
                "document_name",
              
                "extracted_text",
              
            ],
          
        
          
          

          
            "feedback_entries": [
              
                "comment",
              
            ],
          
        
          
          

          
            "tracking_events": [
              
                "event_label",
              
                "page_path",
              
                "metadata_json",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
            "membership_plans": [
              
                "price_amount",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "lessons": [
              
                "order_index",
              
            ],
          
        
          
          
          
        
          
          
          
            "lesson_progress": [
              
                "progress_percent",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "ai_gateways": [
              
                "default_daily_request_limit",
              
                "default_daily_cost_limit",
              
            ],
          
        
          
          
          
            "usage_limit_policies": [
              
                "daily_request_limit",
              
                "monthly_request_limit",
              
                "daily_cost_limit",
              
                "monthly_cost_limit",
              
            ],
          
        
          
          
          
            "ai_tasks": [
              
                "per_user_daily_limit",
              
            ],
          
        
          
          
          
            "ai_requests": [
              
                "prompt_tokens",
              
                "completion_tokens",
              
                "estimated_cost",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "feedback_entries": [
              
                "score",
              
            ],
          
        
          
          
          
        
      };

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