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": [
              
                "brand_name",
              
                "website_url",
              
                "industry",
              
                "primary_market",
              
            ],
          
        
          
          

          
            "brand_voice_profiles": [
              
                "profile_name",
              
                "voice_description",
              
                "do_say_examples",
              
                "dont_say_examples",
              
            ],
          
        
          
          

          
            "brain_profiles": [
              
                "profile_name",
              
                "goal_statement",
              
                "behavior_rules",
              
                "preferred_sources_description",
              
            ],
          
        
          
          

          
            "skill_modules": [
              
                "module_name",
              
                "module_description",
              
                "method_steps",
              
            ],
          
        
          
          

          
            "six_hat_sessions": [
              
                "session_name",
              
                "prompt_context",
              
                "white_hat_notes",
              
                "red_hat_notes",
              
                "black_hat_notes",
              
                "yellow_hat_notes",
              
                "green_hat_notes",
              
                "blue_hat_notes",
              
            ],
          
        
          
          

          
            "knowledge_sources": [
              
                "source_name",
              
                "source_url",
              
                "refresh_notes",
              
            ],
          
        
          
          

          
            "knowledge_documents": [
              
                "document_title",
              
                "language",
              
                "document_summary",
              
                "tags_csv",
              
            ],
          
        
          
          

          
            "knowledge_chunks": [
              
                "chunk_label",
              
                "chunk_text",
              
                "source_locator",
              
            ],
          
        
          
          

          
            "knowledge_nodes": [
              
                "node_name",
              
                "node_description",
              
            ],
          
        
          
          

          
            "campaigns": [
              
                "campaign_name",
              
                "objective",
              
                "primary_audience",
              
                "budget_currency",
              
            ],
          
        
          
          

          
            "campaign_brain_configs": [
              
                "layer_name",
              
            ],
          
        
          
          

          
            "safety_policies": [
              
                "policy_name",
              
                "policy_rules",
              
                "restricted_topics",
              
                "never_copy_sources",
              
            ],
          
        
          
          

          
            "audit_events": [
              
                "event_summary",
              
                "event_details",
              
            ],
          
        
          
          

          
            "ad_projects": [
              
                "project_name",
              
                "creative_brief",
              
            ],
          
        
          
          

          
            "ad_creatives": [
              
                "creative_name",
              
                "primary_text",
              
                "headline",
              
                "description_text",
              
                "call_to_action",
              
                "targeting_notes",
              
            ],
          
        
          
          

          
            "generation_runs": [
              
                "input_prompt",
              
                "model_label",
              
            ],
          
        
          
          

          
            "generation_outputs": [
              
                "output_title",
              
                "output_content",
              
            ],
          
        
          
          

          
            "output_citations": [
              
                "citation_note",
              
            ],
          
        
          
          

          
            "feedback_entries": [
              
                "freeform_notes",
              
            ],
          
        
          
          

          
            "learning_signals": [
              
                "signal_title",
              
                "signal_details",
              
            ],
          
        
          
          

          
        
          
          

          
            "sandbox_scenarios": [
              
                "scenario_name",
              
                "scenario_description",
              
            ],
          
        
          
          

          
            "refresh_jobs": [
              
                "job_summary",
              
                "job_log",
              
            ],
          
        
          
          

          
            "approval_reviews": [
              
                "review_notes",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
            "brand_voice_profiles": [
              
                "reading_level_target",
              
                "formality_level",
              
                "empathy_level",
              
                "energy_level",
              
                "humor_level",
              
                "risk_tolerance",
              
            ],
          
        
          
          
          
            "brain_profiles": [
              
                "citation_strictness",
              
                "creativity_level",
              
                "compliance_strictness",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "knowledge_chunks": [
              
                "recency_weight",
              
                "quality_score",
              
            ],
          
        
          
          
          
            "knowledge_nodes": [
              
                "importance_score",
              
            ],
          
        
          
          
          
            "campaigns": [
              
                "budget_amount",
              
            ],
          
        
          
          
          
            "campaign_brain_configs": [
              
                "priority_order",
              
                "influence_weight",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "generation_runs": [
              
                "temperature",
              
                "retrieved_chunk_count",
              
            ],
          
        
          
          
          
        
          
          
          
            "output_citations": [
              
                "relevance_score",
              
            ],
          
        
          
          
          
            "feedback_entries": [
              
                "overall_score",
              
                "compliance_score",
              
                "brand_fit_score",
              
                "conversion_intent_score",
              
                "empathy_score",
              
                "risk_boldness_score",
              
            ],
          
        
          
          
          
            "learning_signals": [
              
                "confidence_score",
              
            ],
          
        
          
          
          
            "platform_metrics": [
              
                "spend",
              
                "impressions",
              
                "clicks",
              
                "ctr",
              
                "conversions",
              
                "cpa",
              
                "roas",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "approval_reviews": [
              
                "alignment_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;
    }
  }
}