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

          
            "admins": [
              
                "full_name",
              
                "gmail_address",
              
                "department",
              
            ],
          
        
          
          

          
            "city_doctors": [
              
                "full_name",
              
                "hospital_code",
              
                "doctor_registration_no",
              
                "specialization",
              
                "qualification",
              
                "clinic_address",
              
            ],
          
        
          
          

          
            "rural_doctors": [
              
                "full_name",
              
                "dho_code",
              
                "doctor_registration_no",
              
                "assigned_region",
              
                "subcenter_name",
              
            ],
          
        
          
          

          
            "patients": [
              
                "patient_uid",
              
                "full_name",
              
                "blood_group",
              
                "allergies",
              
                "chronic_conditions",
              
                "emergency_contact_name",
              
                "emergency_contact_phone",
              
            ],
          
        
          
          

          
            "medical_reports": [
              
                "chief_complaint",
              
                "symptoms",
              
                "diagnosis",
              
                "clinical_notes",
              
                "prescription_notes",
              
                "recommended_tests",
              
            ],
          
        
          
          

          
            "medicines": [
              
                "medicine_name",
              
                "generic_name",
              
                "strength",
              
                "unit",
              
                "manufacturer",
              
                "storage_instructions",
              
            ],
          
        
          
          

          
            "inventory_updates": [
              
                "reason",
              
            ],
          
        
          
          

          
            "medicine_dispatches": [
              
                "dispatch_note",
              
                "destination_address",
              
                "tracking_reference",
              
            ],
          
        
          
          

          
            "dispatch_items": [
              
                "dosage_instructions",
              
            ],
          
        
          
          

          
            "medical_camps": [
              
                "camp_name",
              
                "location_name",
              
                "address",
              
                "services_offered",
              
                "notes",
              
            ],
          
        
          
          

          
            "appointments": [
              
                "reason_for_visit",
              
                "meeting_link",
              
                "meeting_room",
              
            ],
          
        
          
          

          
            "chat_threads": [
              
                "thread_title",
              
            ],
          
        
          
          

          
            "messages": [
              
                "message_text",
              
            ],
          
        
          
          

          
            "notifications": [
              
                "title_text",
              
                "body_text",
              
                "action_url",
              
            ],
          
        
          
          

          
            "trucks": [
              
                "truck_code",
              
                "registration_number",
              
                "driver_name",
              
                "driver_phone",
              
            ],
          
        
          
          

          
            "truck_tracking_events": [
              
                "heading",
              
                "event_note",
              
            ],
          
        
          
          

          
            "vaccination_reminders": [
              
                "vaccine_name",
              
                "notes",
              
            ],
          
        
          
          

          
            "medicine_reminders": [
              
                "medicine_label",
              
                "dosage",
              
                "instructions",
              
            ],
          
        
          
          

          
            "ai_chat_sessions": [
              
                "summary",
              
            ],
          
        
          
          

          
            "ai_chat_messages": [
              
                "message_text",
              
            ],
          
        
          
          

          
            "audit_logs": [
              
                "entity_name",
              
                "entity_reference",
              
                "ip_address",
              
                "user_agent",
              
                "details",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
            "city_doctors": [
              
                "years_experience",
              
                "consultation_fee",
              
                "clinic_latitude",
              
                "clinic_longitude",
              
            ],
          
        
          
          
          
            "rural_doctors": [
              
                "subcenter_latitude",
              
                "subcenter_longitude",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "medicines": [
              
                "unit_price",
              
                "reorder_level",
              
            ],
          
        
          
          
          
            "inventory_updates": [
              
                "quantity_change",
              
                "quantity_after",
              
            ],
          
        
          
          
          
            "medicine_dispatches": [
              
                "destination_latitude",
              
                "destination_longitude",
              
            ],
          
        
          
          
          
            "dispatch_items": [
              
                "quantity",
              
            ],
          
        
          
          
          
            "medical_camps": [
              
                "latitude",
              
                "longitude",
              
                "expected_attendees",
              
                "actual_attendees",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "trucks": [
              
                "last_latitude",
              
                "last_longitude",
              
            ],
          
        
          
          
          
            "truck_tracking_events": [
              
                "latitude",
              
                "longitude",
              
                "speed_kph",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
      };

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