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

          
            "patients": [
              
                "full_name",
              
                "national_number",
              
                "phone",
              
                "address",
              
            ],
          
        
          
          

          
            "guarantors": [
              
                "name",
              
                "national_number",
              
                "phone",
              
                "address",
              
            ],
          
        
          
          

          
            "doctors": [
              
                "full_name",
              
                "national_number",
              
                "specialty",
              
            ],
          
        
          
          

          
            "visits": [
              
                "visit_number",
              
                "blood_pressure",
              
                "chief_complaint",
              
                "initial_diagnosis",
              
                "emergency_treatment",
              
                "fluids_iv",
              
                "notes",
              
            ],
          
        
          
          

          
            "orders": [
              
                "order_number",
              
                "subtype",
              
            ],
          
        
          
          

          
            "radiology_types": [
              
                "name",
              
                "notes",
              
            ],
          
        
          
          

          
            "radiology_studies": [
              
                "study_number",
              
                "report_summary",
              
            ],
          
        
          
          

          
            "ct_types": [
              
                "name",
              
            ],
          
        
          
          

          
            "ct_studies": [
              
                "ct_number",
              
                "result_text",
              
            ],
          
        
          
          

          
            "lab_tests": [
              
                "code",
              
                "name",
              
                "unit",
              
                "reference_range",
              
                "notes",
              
            ],
          
        
          
          

          
            "lab_orders": [
              
                "lab_order_number",
              
            ],
          
        
          
          

          
            "lab_results": [
              
                "result_value",
              
                "unit",
              
                "reference_range",
              
                "remarks",
              
            ],
          
        
          
          

          
            "endoscopy_cases": [
              
                "case_number",
              
                "diagnosis",
              
                "procedure_details",
              
                "recommendations",
              
            ],
          
        
          
          

          
            "surgery_cases": [
              
                "case_number",
              
                "surgical_details",
              
            ],
          
        
          
          

          
            "surgery_consumables": [
              
                "name",
              
            ],
          
        
          
          

          
            "anesthesia_records": [
              
                "medications",
              
                "recovery_notes",
              
            ],
          
        
          
          

          
            "cathlab_cases": [
              
                "case_number",
              
                "procedure_details",
              
            ],
          
        
          
          

          
            "ecg_stress_tests": [
              
                "test_number",
              
                "result_text",
              
            ],
          
        
          
          

          
            "nursing_staff": [
              
                "full_name",
              
                "national_number",
              
                "specialty",
              
                "address",
              
                "phone",
              
            ],
          
        
          
          

          
            "cleaning_staff": [
              
                "full_name",
              
                "national_number",
              
                "phone",
              
                "address",
              
            ],
          
        
          
          

          
            "inventory_consumables": [
              
                "name",
              
                "last_supplier",
              
            ],
          
        
          
          

          
            "pharmacy_inventory": [
              
                "drug_name",
              
                "supplier",
              
                "batch_number",
              
            ],
          
        
          
          

          
            "pharmacy_sales_invoices": [
              
                "invoice_number",
              
                "items",
              
            ],
          
        
          
          

          
            "suppliers": [
              
                "name",
              
                "phone",
              
                "address",
              
            ],
          
        
          
          

          
            "purchases": [
              
                "purchase_number",
              
                "items",
              
            ],
          
        
          
          

          
            "patient_invoices": [
              
                "invoice_number",
              
                "items",
              
            ],
          
        
          
          

          
            "ledger_entries": [
              
                "entry_number",
              
                "account",
              
                "description",
              
            ],
          
        
          
          

          
            "journal_entries": [
              
                "journal_number",
              
                "entries",
              
            ],
          
        
          
          

          
            "trial_balances": [
              
                "report_name",
              
                "notes",
              
            ],
          
        
          
          

          
            "closing_balances": [
              
                "report_name",
              
                "notes",
              
            ],
          
        
          
          

          
            "inpatient_rooms": [
              
                "room_number",
              
                "ward_name",
              
            ],
          
        
          
          

          
            "room_bookings": [
              
                "booking_number",
              
            ],
          
        
          
          

          
            "restaurant_meals": [
              
                "name",
              
            ],
          
        
          
          

          
            "restaurant_inventory": [
              
                "name",
              
                "unit",
              
            ],
          
        
          
          

          
            "maternity_cases": [
              
                "case_number",
              
                "diagnosis",
              
            ],
          
        
          
          

          
            "pregnancy_followups": [
              
                "followup_number",
              
                "blood_pressure",
              
                "delivery_plan",
              
                "notes",
              
            ],
          
        
          
          

          
            "nicu_incubators": [
              
                "incubator_number",
              
                "baby_name",
              
                "baby_age",
              
                "medications",
              
                "devices",
              
                "cancellation_reason",
              
            ],
          
        
          
          

          
            "daily_followup_clinic": [
              
                "record_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "audit_log": [
              
                "action",
              
                "entity",
              
                "entity_ref",
              
                "details",
              
            ],
          
        
          
          

          
            "settings": [
              
                "key",
              
                "value",
              
                "theme_color",
              
                "hospital_name",
              
                "phone",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
            "doctors": [
              
                "visit_price",
              
            ],
          
        
          
          
          
            "visits": [
              
                "visit_price",
              
                "glucose",
              
                "pulse",
              
                "temperature",
              
                "spo2",
              
            ],
          
        
          
          
          
            "orders": [
              
                "price",
              
            ],
          
        
          
          
          
            "radiology_types": [
              
                "price",
              
            ],
          
        
          
          
          
            "radiology_studies": [
              
                "price",
              
            ],
          
        
          
          
          
            "ct_types": [
              
                "price",
              
            ],
          
        
          
          
          
            "ct_studies": [
              
                "price",
              
            ],
          
        
          
          
          
            "lab_tests": [
              
                "price",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "endoscopy_cases": [
              
                "price",
              
            ],
          
        
          
          
          
            "surgery_cases": [
              
                "price",
              
            ],
          
        
          
          
          
            "surgery_consumables": [
              
                "quantity",
              
                "unit_price",
              
                "total_price",
              
            ],
          
        
          
          
          
            "anesthesia_records": [
              
                "price",
              
            ],
          
        
          
          
          
            "cathlab_cases": [
              
                "price",
              
            ],
          
        
          
          
          
            "ecg_stress_tests": [
              
                "price",
              
            ],
          
        
          
          
          
            "nursing_staff": [
              
                "children_count",
              
                "salary",
              
                "bonuses",
              
            ],
          
        
          
          
          
            "cleaning_staff": [
              
                "salary",
              
                "bonuses",
              
            ],
          
        
          
          
          
            "inventory_consumables": [
              
                "received_quantity",
              
                "available_quantity",
              
                "shortage",
              
            ],
          
        
          
          
          
            "pharmacy_inventory": [
              
                "wholesale_price",
              
                "retail_price",
              
                "quantity",
              
            ],
          
        
          
          
          
            "pharmacy_sales_invoices": [
              
                "total_amount",
              
                "tax",
              
                "final_price",
              
            ],
          
        
          
          
          
        
          
          
          
            "purchases": [
              
                "total",
              
            ],
          
        
          
          
          
            "patient_invoices": [
              
                "subtotal",
              
                "tax",
              
                "total",
              
                "print_price",
              
            ],
          
        
          
          
          
            "ledger_entries": [
              
                "debit",
              
                "credit",
              
            ],
          
        
          
          
          
            "journal_entries": [
              
                "total_debit",
              
                "total_credit",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "inpatient_rooms": [
              
                "price_per_day",
              
                "capacity",
              
            ],
          
        
          
          
          
            "room_bookings": [
              
                "days",
              
                "price_per_day",
              
                "total_price",
              
            ],
          
        
          
          
          
            "restaurant_meals": [
              
                "quantity_received",
              
                "quantity_kg",
              
                "shortage",
              
                "estimated_cost",
              
                "distributed_count",
              
                "drinks_count",
              
            ],
          
        
          
          
          
            "restaurant_inventory": [
              
                "quantity_received",
              
                "quantity_kg",
              
                "shortage",
              
            ],
          
        
          
          
          
            "maternity_cases": [
              
                "price",
              
            ],
          
        
          
          
          
            "pregnancy_followups": [
              
                "weight",
              
                "price",
              
            ],
          
        
          
          
          
            "nicu_incubators": [
              
                "daily_price",
              
            ],
          
        
          
          
          
            "daily_followup_clinic": [
              
                "price",
              
            ],
          
        
          
          
          
        
          
          
          
        
      };

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