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

          
            "organizations": [
              
                "name",
              
            ],
          
        
          
          

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

          
            "departments": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "staff_profiles": [
              
                "job_title",
              
                "employee_code",
              
            ],
          
        
          
          

          
            "shifts": [
              
                "notes",
              
            ],
          
        
          
          

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

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

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

          
            "guest_documents": [
              
                "document_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "rate_plans": [
              
                "name",
              
                "cancellation_policy",
              
            ],
          
        
          
          

          
        
          
          

          
            "dynamic_pricing_rules": [
              
                "name",
              
                "applies_days_of_week",
              
            ],
          
        
          
          

          
            "sales_channels": [
              
                "name",
              
                "external_reference",
              
            ],
          
        
          
          

          
            "ota_connections": [
              
                "account_identifier",
              
                "api_key_reference",
              
            ],
          
        
          
          

          
            "reservations": [
              
                "reservation_number",
              
                "special_requests",
              
                "internal_notes",
              
                "cancellation_reason",
              
            ],
          
        
          
          

          
        
          
          

          
            "stay_folios": [
              
                "folio_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "folio_items": [
              
                "description",
              
            ],
          
        
          
          

          
            "payments": [
              
                "stripe_payment_intent_reference",
              
                "stripe_charge_reference",
              
                "receipt_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "refunds": [
              
                "stripe_refund_reference",
              
                "reason",
              
            ],
          
        
          
          

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

          
            "housekeeping_tasks": [
              
                "notes",
              
            ],
          
        
          
          

          
            "maintenance_tickets": [
              
                "title",
              
                "description",
              
            ],
          
        
          
          

          
            "notifications": [
              
                "to_address",
              
                "subject",
              
                "body",
              
                "provider_message_reference",
              
                "error_message",
              
            ],
          
        
          
          

          
            "booking_widgets": [
              
                "name",
              
                "public_key",
              
                "allowed_domains",
              
            ],
          
        
          
          

          
            "subscriptions": [
              
                "stripe_subscription_reference",
              
                "stripe_price_reference",
              
            ],
          
        
          
          

          
            "audit_logs": [
              
                "entity_name",
              
                "record_reference",
              
                "ip_address",
              
                "user_agent",
              
                "details",
              
            ],
          
        
          
          

          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
            "hotels": [
              
                "default_tax_rate",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "room_types": [
              
                "capacity_adults",
              
                "capacity_children",
              
                "base_rate",
              
            ],
          
        
          
          
          
        
          
          
          
            "guests": [
              
                "loyalty_points",
              
            ],
          
        
          
          
          
        
          
          
          
            "rate_plans": [
              
                "min_nights",
              
                "max_nights",
              
                "deposit_percent",
              
            ],
          
        
          
          
          
            "seasonal_rates": [
              
                "nightly_rate",
              
                "delta_amount",
              
            ],
          
        
          
          
          
            "dynamic_pricing_rules": [
              
                "adjustment_percent",
              
                "adjustment_amount",
              
                "min_occupancy_percent",
              
                "max_occupancy_percent",
              
                "min_days_before",
              
                "max_days_before",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "reservations": [
              
                "adults",
              
                "children",
              
                "total_amount",
              
                "tax_amount",
              
                "deposit_amount",
              
            ],
          
        
          
          
          
        
          
          
          
            "stay_folios": [
              
                "balance_due",
              
                "total_charges",
              
                "total_payments",
              
            ],
          
        
          
          
          
            "folio_items": [
              
                "quantity",
              
                "unit_price",
              
                "amount",
              
            ],
          
        
          
          
          
            "payments": [
              
                "amount",
              
            ],
          
        
          
          
          
            "refunds": [
              
                "amount",
              
            ],
          
        
          
          
          
            "invoices": [
              
                "subtotal_amount",
              
                "tax_amount",
              
                "total_amount",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "subscriptions": [
              
                "included_rooms_limit",
              
                "included_users_limit",
              
            ],
          
        
          
          
          
        
          
          
          
            "daily_snapshots": [
              
                "rooms_available",
              
                "rooms_occupied",
              
                "rooms_dirty",
              
                "rooms_out_of_service",
              
                "occupancy_rate_percent",
              
                "revenue_today",
              
                "revenue_month_to_date",
              
                "adr",
              
                "revpar",
              
                "arrivals_today",
              
                "departures_today",
              
            ],
          
        
      };

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