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

          
            "tenants": [
              
                "name",
              
                "slug",
              
                "legal_name",
              
                "primary_domain",
              
                "timezone",
              
                "default_currency",
              
            ],
          
        
          
          

          
        
          
          

          
            "organization_memberships": [
              
                "job_title",
              
                "phone",
              
            ],
          
        
          
          

          
            "properties": [
              
                "name",
              
                "code",
              
                "address",
              
                "city",
              
                "country",
              
                "timezone",
              
                "description",
              
            ],
          
        
          
          

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

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

          
            "units": [
              
                "unit_number",
              
                "floor",
              
                "notes",
              
            ],
          
        
          
          

          
            "unit_availability_blocks": [
              
                "reason",
              
            ],
          
        
          
          

          
            "negotiated_rates": [
              
                "notes",
              
            ],
          
        
          
          

          
            "booking_requests": [
              
                "request_code",
              
                "purpose_of_stay",
              
                "special_requirements",
              
                "budget_code",
              
                "currency",
              
            ],
          
        
          
          

          
            "booking_request_travelers": [
              
                "full_name",
              
                "email",
              
                "phone",
              
                "nationality",
              
                "passport_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "approval_steps": [
              
                "decision_notes",
              
            ],
          
        
          
          

          
            "reservations": [
              
                "reservation_code",
              
                "currency",
              
                "internal_notes",
              
                "external_notes",
              
            ],
          
        
          
          

          
            "reservation_guests": [
              
                "full_name",
              
                "email",
              
                "phone",
              
                "notes",
              
            ],
          
        
          
          

          
            "service_requests": [
              
                "summary",
              
                "details",
              
                "currency",
              
            ],
          
        
          
          

          
            "invoices": [
              
                "invoice_number",
              
                "currency",
              
                "bill_to_name",
              
                "bill_to_address",
              
                "notes",
              
            ],
          
        
          
          

          
            "invoice_line_items": [
              
                "description",
              
                "service_period",
              
            ],
          
        
          
          

          
            "payments": [
              
                "currency",
              
                "reference",
              
                "notes",
              
            ],
          
        
          
          

          
            "documents": [
              
                "file_name",
              
                "mime_type",
              
                "storage_key",
              
                "public_url",
              
                "notes",
              
            ],
          
        
          
          

          
            "audit_logs": [
              
                "action",
              
                "entity_name",
              
                "entity_reference",
              
                "ip_address",
              
                "user_agent",
              
                "metadata_json",
              
            ],
          
        
          
          

          
            "notifications": [
              
                "title",
              
                "body",
              
                "link_url",
              
            ],
          
        
          
          

          
            "activity_comments": [
              
                "body",
              
            ],
          
        
          
          

          
            "checklists": [
              
                "notes",
              
            ],
          
        
          
          

          
            "checklist_items": [
              
                "title",
              
                "notes",
              
            ],
          
        
          
          

          
            "job_runs": [
              
                "last_error",
              
                "payload_json",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "unit_types": [
              
                "max_occupancy",
              
                "bedrooms",
              
                "bathrooms",
              
                "size_sqm",
              
                "base_nightly_rate",
              
                "base_monthly_rate",
              
                "minimum_stay_nights",
              
            ],
          
        
          
          
          
            "units": [
              
                "max_occupancy_override",
              
            ],
          
        
          
          
          
        
          
          
          
            "negotiated_rates": [
              
                "rate_amount",
              
                "minimum_stay_nights",
              
            ],
          
        
          
          
          
            "booking_requests": [
              
                "preferred_bedrooms",
              
                "guest_count",
              
                "max_budget_amount",
              
            ],
          
        
          
          
          
        
          
          
          
            "approval_steps": [
              
                "step_order",
              
            ],
          
        
          
          
          
            "reservations": [
              
                "guest_count",
              
                "nightly_rate",
              
                "monthly_rate",
              
            ],
          
        
          
          
          
        
          
          
          
            "service_requests": [
              
                "estimated_cost",
              
                "actual_cost",
              
            ],
          
        
          
          
          
            "invoices": [
              
                "subtotal_amount",
              
                "tax_amount",
              
                "total_amount",
              
                "balance_due",
              
            ],
          
        
          
          
          
            "invoice_line_items": [
              
                "quantity",
              
                "unit_price",
              
                "amount",
              
            ],
          
        
          
          
          
            "payments": [
              
                "amount",
              
            ],
          
        
          
          
          
            "documents": [
              
                "file_size_bytes",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "checklist_items": [
              
                "sort_order",
              
            ],
          
        
          
          
          
            "job_runs": [
              
                "attempt_count",
              
            ],
          
        
      };

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