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

          
            "school_settings": [
              
                "school_name_om",
              
                "school_name_am",
              
                "school_name_en",
              
                "welcome_message_om",
              
                "welcome_message_am",
              
                "welcome_message_en",
              
                "address_text",
              
                "map_embed_url",
              
                "public_phone_numbers",
              
                "public_emails",
              
                "social_links",
              
            ],
          
        
          
          

          
            "pages": [
              
                "title_om",
              
                "title_am",
              
                "title_en",
              
                "content_om",
              
                "content_am",
              
                "content_en",
              
            ],
          
        
          
          

          
            "school_years": [
              
                "name",
              
            ],
          
        
          
          

          
            "grades": [
              
                "label",
              
            ],
          
        
          
          

          
            "streams": [
              
                "name_om",
              
                "name_am",
              
                "name_en",
              
            ],
          
        
          
          

          
            "subjects": [
              
                "name_om",
              
                "name_am",
              
                "name_en",
              
                "overview_om",
              
                "overview_am",
              
                "overview_en",
              
                "textbook_references",
              
            ],
          
        
          
          

          
            "subject_offerings": [
              
                "learning_objectives_om",
              
                "learning_objectives_am",
              
                "learning_objectives_en",
              
                "topics_outline",
              
            ],
          
        
          
          

          
            "staff_members": [
              
                "full_name",
              
                "bio",
              
                "phone_number",
              
                "email",
              
            ],
          
        
          
          

          
            "students": [
              
                "full_name",
              
                "student_code",
              
                "guardian_name",
              
                "guardian_phone",
              
                "address_text",
              
            ],
          
        
          
          

          
            "class_sections": [
              
                "name",
              
            ],
          
        
          
          

          
        
          
          

          
        
          
          

          
            "events": [
              
                "title_om",
              
                "title_am",
              
                "title_en",
              
                "description_om",
              
                "description_am",
              
                "description_en",
              
                "location_text",
              
            ],
          
        
          
          

          
            "announcements": [
              
                "title_om",
              
                "title_am",
              
                "title_en",
              
                "content_om",
              
                "content_am",
              
                "content_en",
              
            ],
          
        
          
          

          
            "news_posts": [
              
                "title_om",
              
                "title_am",
              
                "title_en",
              
                "excerpt_om",
              
                "excerpt_am",
              
                "excerpt_en",
              
                "content_om",
              
                "content_am",
              
                "content_en",
              
            ],
          
        
          
          

          
            "galleries": [
              
                "title_om",
              
                "title_am",
              
                "title_en",
              
                "description_om",
              
                "description_am",
              
                "description_en",
              
            ],
          
        
          
          

          
            "study_materials": [
              
                "title_om",
              
                "title_am",
              
                "title_en",
              
                "description",
              
                "external_url",
              
            ],
          
        
          
          

          
            "exams": [
              
                "name",
              
            ],
          
        
          
          

          
        
          
          

          
            "attendance_sessions": [
              
                "note",
              
            ],
          
        
          
          

          
            "attendance_records": [
              
                "remark",
              
            ],
          
        
          
          

          
            "class_schedules": [
              
                "period_label",
              
                "room",
              
            ],
          
        
          
          

          
            "assignments": [
              
                "title",
              
                "instructions",
              
            ],
          
        
          
          

          
            "assignment_submissions": [
              
                "comment",
              
                "teacher_feedback",
              
            ],
          
        
          
          

          
            "lesson_plans": [
              
                "plan_content",
              
            ],
          
        
          
          

          
            "messages": [
              
                "subject",
              
                "body",
              
            ],
          
        
          
          

          
            "admission_applications": [
              
                "applicant_full_name",
              
                "previous_school",
              
                "guardian_full_name",
              
                "guardian_phone",
              
                "guardian_email",
              
                "address_text",
              
            ],
          
        
          
          

          
            "contact_messages": [
              
                "full_name",
              
                "phone_number",
              
                "email",
              
                "message",
              
            ],
          
        
          
          

          
            "alumni": [
              
                "full_name",
              
                "graduation_year",
              
                "current_role",
              
                "organization",
              
                "bio",
              
                "phone_number",
              
                "email",
              
            ],
          
        
          
          

          
            "school_statistics": [
              
                "notes",
              
            ],
          
        
          
          

          
        
          
          

          
            "top_student_features": [
              
                "note",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "grades": [
              
                "grade_number",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "class_sections": [
              
                "capacity",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "exam_results": [
              
                "score",
              
                "out_of",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "assignment_submissions": [
              
                "grade_value",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "school_statistics": [
              
                "student_count",
              
                "teacher_count",
              
                "pass_rate",
              
            ],
          
        
          
          
          
            "exam_performance_summaries": [
              
                "average_score",
              
                "highest_score",
              
                "lowest_score",
              
                "pass_rate",
              
                "student_count",
              
            ],
          
        
          
          
          
            "top_student_features": [
              
                "total_score",
              
                "rank",
              
            ],
          
        
      };

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