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

          
            "languages": [
              
                "name",
              
                "locale",
              
            ],
          
        
          
          

          
            "gdpr_consents": [
              
                "consent_version",
              
                "ip_address",
              
                "user_agent",
              
            ],
          
        
          
          

          
            "gdpr_requests": [
              
                "details",
              
            ],
          
        
          
          

          
            "audit_logs": [
              
                "entity_name",
              
                "record_key",
              
                "summary",
              
                "ip_address",
              
                "user_agent",
              
            ],
          
        
          
          

          
            "hotels": [
              
                "name",
              
                "legal_name",
              
                "tax_number",
              
                "email",
              
                "phone",
              
                "website",
              
                "address_line1",
              
                "address_line2",
              
                "city",
              
                "state_region",
              
                "postal_code",
              
                "country",
              
                "timezone",
              
                "description",
              
            ],
          
        
          
          

          
            "room_types": [
              
                "name",
              
                "code",
              
                "short_description",
              
                "description",
              
            ],
          
        
          
          

          
            "rooms": [
              
                "room_number",
              
                "floor",
              
                "notes",
              
            ],
          
        
          
          

          
            "amenities": [
              
                "name",
              
                "code",
              
                "description",
              
            ],
          
        
          
          

          
            "room_features": [
              
                "name",
              
                "code",
              
            ],
          
        
          
          

          
            "rate_plans": [
              
                "name",
              
                "code",
              
                "cancellation_policy_text",
              
            ],
          
        
          
          

          
            "seasonal_rates": [
              
                "name",
              
                "currency",
              
            ],
          
        
          
          

          
            "inventory_blocks": [
              
                "name",
              
                "reason",
              
            ],
          
        
          
          

          
            "guests": [
              
                "email",
              
                "phone",
              
                "first_name",
              
                "last_name",
              
                "nationality",
              
                "address_line1",
              
                "address_line2",
              
                "city",
              
                "state_region",
              
                "postal_code",
              
                "country",
              
                "identity_document_number",
              
            ],
          
        
          
          

          
            "bookings": [
              
                "booking_code",
              
                "currency",
              
                "special_requests",
              
                "cancellation_reason",
              
            ],
          
        
          
          

          
        
          
          

          
            "payments": [
              
                "currency",
              
                "provider_reference",
              
                "receipt_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "invoices": [
              
                "invoice_number",
              
                "currency",
              
                "billing_name",
              
                "billing_address",
              
                "billing_tax_number",
              
            ],
          
        
          
          

          
            "messages": [
              
                "subject",
              
                "body",
              
                "to_address",
              
                "from_address",
              
                "provider_reference",
              
            ],
          
        
          
          

          
            "promo_codes": [
              
                "code",
              
                "name",
              
                "currency",
              
            ],
          
        
          
          

          
            "booking_discounts": [
              
                "currency",
              
            ],
          
        
          
          

          
            "housekeeping_tasks": [
              
                "notes",
              
            ],
          
        
          
          

          
            "service_requests": [
              
                "title",
              
                "description",
              
            ],
          
        
          
          

          
            "content_pages": [
              
                "title",
              
                "slug",
              
                "content",
              
            ],
          
        
          
          

          
            "settings": [
              
                "key",
              
                "value",
              
                "description",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "room_types": [
              
                "max_occupancy",
              
                "max_adults",
              
                "max_children",
              
                "bed_count",
              
                "base_area_sqm",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "rate_plans": [
              
                "min_stay_nights",
              
                "max_stay_nights",
              
                "release_days",
              
            ],
          
        
          
          
          
            "seasonal_rates": [
              
                "price_amount",
              
                "min_stay_nights",
              
                "max_stay_nights",
              
            ],
          
        
          
          
          
            "inventory_blocks": [
              
                "rooms_blocked",
              
            ],
          
        
          
          
          
        
          
          
          
            "bookings": [
              
                "adults",
              
                "children",
              
                "total_amount",
              
                "tax_amount",
              
                "city_tax_amount",
              
                "deposit_amount",
              
            ],
          
        
          
          
          
        
          
          
          
            "payments": [
              
                "amount",
              
            ],
          
        
          
          
          
            "invoices": [
              
                "subtotal_amount",
              
                "tax_amount",
              
                "total_amount",
              
            ],
          
        
          
          
          
        
          
          
          
            "promo_codes": [
              
                "discount_value",
              
                "max_uses",
              
                "max_uses_per_guest",
              
                "min_nights",
              
            ],
          
        
          
          
          
            "booking_discounts": [
              
                "discount_value",
              
                "discount_amount",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
      };

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