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

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

          
        
          
          

          
            "subjects": [
              
                "name",
              
                "color_hex",
              
            ],
          
        
          
          

          
            "topics": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "pages": [
              
                "title",
              
                "icon_emoji",
              
            ],
          
        
          
          

          
            "blocks": [
              
                "title",
              
                "text_content",
              
                "code_language",
              
                "link_url",
              
            ],
          
        
          
          

          
            "databases": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "database_entries": [
              
                "title",
              
                "summary",
              
            ],
          
        
          
          

          
            "sources": [
              
                "title",
              
                "source_url",
              
                "error_message",
              
            ],
          
        
          
          

          
            "source_chunks": [
              
                "chunk_text",
              
                "embedding_provider",
              
                "embedding_model",
              
            ],
          
        
          
          

          
            "ai_jobs": [
              
                "provider",
              
                "model",
              
                "error_details",
              
            ],
          
        
          
          

          
            "concept_maps": [
              
                "title",
              
                "map_data_json",
              
            ],
          
        
          
          

          
            "study_guides": [
              
                "title",
              
                "content",
              
            ],
          
        
          
          

          
            "flashcard_decks": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "flashcards": [
              
                "front",
              
                "back",
              
                "hint",
              
            ],
          
        
          
          

          
        
          
          

          
        
          
          

          
        
          
          

          
            "quizzes": [
              
                "title",
              
            ],
          
        
          
          

          
            "quiz_questions": [
              
                "prompt",
              
                "choices_json",
              
                "correct_answer",
              
                "explanation",
              
            ],
          
        
          
          

          
        
          
          

          
            "tutor_conversations": [
              
                "title",
              
            ],
          
        
          
          

          
            "tutor_messages": [
              
                "content",
              
                "citations_json",
              
            ],
          
        
          
          

          
            "study_plans": [
              
                "title",
              
                "goal",
              
            ],
          
        
          
          

          
            "study_plan_items": [
              
                "title",
              
            ],
          
        
          
          

          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "blocks": [
              
                "sort_order",
              
            ],
          
        
          
          
          
        
          
          
          
            "database_entries": [
              
                "estimated_retention",
              
            ],
          
        
          
          
          
        
          
          
          
            "source_chunks": [
              
                "chunk_index",
              
                "token_count_estimate",
              
            ],
          
        
          
          
          
            "ai_jobs": [
              
                "cost_estimate",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "flashcards": [
              
                "sort_order",
              
            ],
          
        
          
          
          
            "spaced_repetition_states": [
              
                "repetitions",
              
                "lapses",
              
                "ease_factor",
              
                "interval_days",
              
                "stability",
              
                "difficulty",
              
            ],
          
        
          
          
          
            "study_sessions": [
              
                "duration_seconds",
              
                "focus_score",
              
            ],
          
        
          
          
          
            "review_events": [
              
                "response_time_ms",
              
            ],
          
        
          
          
          
            "quizzes": [
              
                "time_limit_minutes",
              
            ],
          
        
          
          
          
            "quiz_questions": [
              
                "points",
              
                "sort_order",
              
            ],
          
        
          
          
          
            "quiz_attempts": [
              
                "score_percent",
              
                "correct_count",
              
                "total_count",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "study_plans": [
              
                "target_hours_per_week",
              
            ],
          
        
          
          
          
            "study_plan_items": [
              
                "estimated_minutes",
              
            ],
          
        
          
          
          
            "dashboard_snapshots": [
              
                "study_hours_last_7d",
              
                "study_hours_last_30d",
              
                "retention_estimate",
              
                "test_performance_avg",
              
                "cards_due_count",
              
                "streak_days",
              
            ],
          
        
      };

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