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

          
            "schools": [
              
                "name",
              
            ],
          
        
          
          

          
            "grade_levels": [
              
                "grade_name",
              
            ],
          
        
          
          

          
            "subjects": [
              
                "subject_name",
              
                "subject_code",
              
                "description",
              
            ],
          
        
          
          

          
            "classrooms": [
              
                "classroom_name",
              
                "section_name",
              
                "invite_code",
              
                "room_description",
              
            ],
          
        
          
          

          
            "classroom_memberships": [
              
                "join_method",
              
                "notes",
              
            ],
          
        
          
          

          
        
          
          

          
            "homeworks": [
              
                "homework_title",
              
                "homework_description",
              
            ],
          
        
          
          

          
            "homework_rubrics": [
              
                "criterion_title",
              
                "criterion_description",
              
            ],
          
        
          
          

          
            "homework_extensions": [
              
                "reason",
              
            ],
          
        
          
          

          
            "homework_submissions": [
              
                "submission_text",
              
            ],
          
        
          
          

          
            "submission_grades": [
              
                "teacher_feedback",
              
            ],
          
        
          
          

          
            "rubric_scores": [
              
                "comment",
              
            ],
          
        
          
          

          
            "gradebooks": [
              
                "gradebook_name",
              
            ],
          
        
          
          

          
            "gradebook_columns": [
              
                "column_name",
              
            ],
          
        
          
          

          
            "gradebook_entries": [
              
                "remarks",
              
            ],
          
        
          
          

          
            "adviser_reports": [
              
                "summary_notes",
              
            ],
          
        
          
          

          
            "announcements": [
              
                "announcement_title",
              
                "announcement_body",
              
            ],
          
        
          
          

          
            "notifications": [
              
                "title",
              
                "message",
              
            ],
          
        
          
          

          
            "account_applications": [
              
                "application_notes",
              
            ],
          
        
          
          

          
            "guardians": [
              
                "guardian_name",
              
                "relationship",
              
                "phone_number",
              
                "email",
              
                "address",
              
            ],
          
        
          
          

          
            "security_events": [
              
                "ip_address",
              
                "user_agent",
              
                "details",
              
            ],
          
        
          
          

          
            "support_settings": [
              
                "support_email",
              
                "support_phone",
              
                "support_hours",
              
                "privacy_policy_url",
              
                "terms_url",
              
                "app_version_notes",
              
            ],
          
        
          
          

          
            "feedback_items": [
              
                "feedback_title",
              
                "feedback_message",
              
            ],
          
        
          
          

          
            "events": [
              
                "event_name",
              
                "event_description",
              
            ],
          
        
          
          

          
            "ai_monitoring_rules": [
              
                "rule_name",
              
                "rule_description",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
            "grade_levels": [
              
                "grade_order",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "homeworks": [
              
                "max_score",
              
            ],
          
        
          
          
          
            "homework_rubrics": [
              
                "criterion_max_score",
              
                "sort_order",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "submission_grades": [
              
                "total_score",
              
                "max_score_snapshot",
              
            ],
          
        
          
          
          
            "rubric_scores": [
              
                "score",
              
            ],
          
        
          
          
          
        
          
          
          
            "gradebook_columns": [
              
                "max_score",
              
                "weight",
              
                "sort_order",
              
            ],
          
        
          
          
          
            "gradebook_entries": [
              
                "score",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "feedback_items": [
              
                "rating",
              
            ],
          
        
          
          
          
            "events": [
              
                "price",
              
            ],
          
        
          
          
          
            "ai_monitoring_rules": [
              
                "threshold_value",
              
            ],
          
        
      };

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