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

          
            "onboarding_responses": [
              
                "learning_goals_text",
              
            ],
          
        
          
          

          
            "external_accounts": [
              
                "handle",
              
                "profile_url",
              
                "access_token_hint",
              
            ],
          
        
          
          

          
            "skill_nodes": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "user_skill_node_awards": [
              
                "source_label",
              
                "evidence_url",
              
            ],
          
        
          
          

          
            "projects": [
              
                "name",
              
                "description",
              
                "project_url",
              
                "ai_tools_used",
              
            ],
          
        
          
          

          
            "external_signals": [
              
                "signal_type",
              
                "title",
              
                "summary",
              
                "source_url",
              
            ],
          
        
          
          

          
            "courses": [
              
                "name",
              
                "tagline",
              
                "description",
              
                "hero_image_url",
              
            ],
          
        
          
          

          
            "course_phases": [
              
                "name",
              
                "summary",
              
            ],
          
        
          
          

          
            "lessons": [
              
                "name",
              
                "summary",
              
                "base_content",
              
            ],
          
        
          
          

          
            "lesson_variants": [
              
                "adapted_content",
              
                "adaptation_notes",
              
            ],
          
        
          
          

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

          
            "build_tasks": [
              
                "name",
              
                "instructions",
              
                "expected_deliverable",
              
            ],
          
        
          
          

          
        
          
          

          
        
          
          

          
        
          
          

          
            "task_submissions": [
              
                "submission_text",
              
                "submission_url",
              
                "ai_feedback",
              
            ],
          
        
          
          

          
            "ai_chat_sessions": [
              
                "context_summary",
              
            ],
          
        
          
          

          
            "ai_chat_messages": [
              
                "message_text",
              
            ],
          
        
          
          

          
            "career_coach_reports": [
              
                "resume_text",
              
                "current_role_text",
              
                "target_role_text",
              
                "clarifying_questions",
              
                "career_path",
              
                "skill_gaps",
              
                "next_steps",
              
                "resume_suggestions",
              
                "share_token",
              
            ],
          
        
          
          

          
        
          
          

          
            "pricing_plans": [
              
                "name",
              
                "description",
              
                "currency",
              
                "stripe_price_ref",
              
            ],
          
        
          
          

          
            "subscriptions": [
              
                "stripe_customer_ref",
              
                "stripe_subscription_ref",
              
            ],
          
        
          
          

          
            "payments": [
              
                "currency",
              
                "stripe_payment_intent_ref",
              
                "receipt_url",
              
            ],
          
        
          
          

          
            "cohorts": [
              
                "name",
              
            ],
          
        
          
          

          
        
          
          

          
            "talent_inquiries": [
              
                "subject",
              
                "message",
              
                "contact_email",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "skill_nodes": [
              
                "node_index",
              
            ],
          
        
          
          
          
            "user_skill_node_awards": [
              
                "confidence_score",
              
            ],
          
        
          
          
          
        
          
          
          
            "external_signals": [
              
                "signal_score",
              
            ],
          
        
          
          
          
            "courses": [
              
                "estimated_total_minutes",
              
            ],
          
        
          
          
          
            "course_phases": [
              
                "phase_number",
              
                "estimated_minutes",
              
            ],
          
        
          
          
          
            "lessons": [
              
                "lesson_number",
              
                "estimated_minutes",
              
            ],
          
        
          
          
          
        
          
          
          
            "quiz_questions": [
              
                "order_index",
              
            ],
          
        
          
          
          
            "build_tasks": [
              
                "max_files",
              
            ],
          
        
          
          
          
            "enrollments": [
              
                "progress_percent",
              
            ],
          
        
          
          
          
            "lesson_progress": [
              
                "time_spent_seconds",
              
                "lesson_progress_percent",
              
            ],
          
        
          
          
          
            "quiz_attempts": [
              
                "score_percent",
              
                "correct_count",
              
                "question_count",
              
            ],
          
        
          
          
          
            "task_submissions": [
              
                "ai_score",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "usage_limits": [
              
                "limit_count",
              
                "used_count",
              
            ],
          
        
          
          
          
            "pricing_plans": [
              
                "price_amount",
              
            ],
          
        
          
          
          
        
          
          
          
            "payments": [
              
                "amount",
              
            ],
          
        
          
          
          
            "cohorts": [
              
                "max_learners",
              
            ],
          
        
          
          
          
        
          
          
          
        
      };

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