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": [
              
                "tenant_name",
              
                "slug",
              
                "contact_email",
              
                "contact_phone",
              
                "billing_address",
              
            ],
          
        
          
          

          
        
          
          

          
            "tenant_locations": [
              
                "location_name",
              
                "address",
              
                "timezone",
              
            ],
          
        
          
          

          
            "ponds": [
              
                "pond_name",
              
                "notes",
              
            ],
          
        
          
          

          
            "species": [
              
                "species_name",
              
                "scientific_name",
              
                "typical_harvest_size",
              
            ],
          
        
          
          

          
            "batches": [
              
                "batch_code",
              
                "notes",
              
            ],
          
        
          
          

          
            "feed_products": [
              
                "product_name",
              
                "brand",
              
                "feed_type",
              
                "notes",
              
            ],
          
        
          
          

          
            "inventory_items": [
              
                "item_name",
              
                "sku",
              
                "unit",
              
            ],
          
        
          
          

          
            "inventory_movements": [
              
                "reference",
              
                "notes",
              
            ],
          
        
          
          

          
            "feeding_logs": [
              
                "notes",
              
            ],
          
        
          
          

          
            "water_quality_logs": [
              
                "notes",
              
            ],
          
        
          
          

          
            "health_events": [
              
                "symptoms",
              
                "treatment",
              
            ],
          
        
          
          

          
            "harvests": [
              
                "notes",
              
            ],
          
        
          
          

          
            "marketplace_listings": [
              
                "listing_title",
              
                "description",
              
                "currency",
              
            ],
          
        
          
          

          
            "orders": [
              
                "order_number",
              
                "currency",
              
                "delivery_address",
              
                "buyer_notes",
              
            ],
          
        
          
          

          
            "order_items": [
              
                "notes",
              
            ],
          
        
          
          

          
            "payment_transactions": [
              
                "currency",
              
                "provider",
              
                "provider_reference",
              
                "failure_reason",
              
            ],
          
        
          
          

          
            "shipment_updates": [
              
                "carrier",
              
                "tracking_number",
              
                "status_details",
              
            ],
          
        
          
          

          
            "investments": [
              
                "investment_name",
              
                "currency",
              
                "notes",
              
            ],
          
        
          
          

          
            "api_keys": [
              
                "key_name",
              
                "key_prefix",
              
            ],
          
        
          
          

          
            "webhook_endpoints": [
              
                "endpoint_name",
              
                "url",
              
                "secret",
              
                "event_types",
              
            ],
          
        
          
          

          
            "webhook_deliveries": [
              
                "event_type",
              
                "event_reference",
              
                "request_payload",
              
                "response_body",
              
            ],
          
        
          
          

          
            "email_notifications": [
              
                "to_email",
              
                "subject",
              
                "template_key",
              
                "payload",
              
                "failure_reason",
              
            ],
          
        
          
          

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

          
            "csv_jobs": [
              
                "entity_name",
              
                "error_report",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "tenant_locations": [
              
                "latitude",
              
                "longitude",
              
            ],
          
        
          
          
          
            "ponds": [
              
                "area_sq_m",
              
                "avg_depth_m",
              
            ],
          
        
          
          
          
        
          
          
          
            "batches": [
              
                "initial_count",
              
                "initial_avg_weight_g",
              
            ],
          
        
          
          
          
            "feed_products": [
              
                "protein_percent",
              
                "fat_percent",
              
                "pellet_size_mm",
              
            ],
          
        
          
          
          
            "inventory_items": [
              
                "quantity_on_hand",
              
                "reorder_level",
              
                "unit_cost",
              
            ],
          
        
          
          
          
            "inventory_movements": [
              
                "quantity",
              
            ],
          
        
          
          
          
            "feeding_logs": [
              
                "quantity_kg",
              
            ],
          
        
          
          
          
            "water_quality_logs": [
              
                "temperature_c",
              
                "ph",
              
                "dissolved_oxygen_mg_l",
              
                "salinity_ppt",
              
                "ammonia_mg_l",
              
                "nitrite_mg_l",
              
                "nitrate_mg_l",
              
                "turbidity_ntu",
              
            ],
          
        
          
          
          
            "health_events": [
              
                "mortality_count",
              
            ],
          
        
          
          
          
            "harvests": [
              
                "total_weight_kg",
              
                "total_count",
              
                "avg_weight_g",
              
            ],
          
        
          
          
          
            "marketplace_listings": [
              
                "available_quantity_kg",
              
                "price_per_kg",
              
            ],
          
        
          
          
          
            "orders": [
              
                "subtotal_amount",
              
                "tax_amount",
              
                "shipping_amount",
              
                "total_amount",
              
            ],
          
        
          
          
          
            "order_items": [
              
                "quantity_kg",
              
                "unit_price",
              
                "line_total",
              
            ],
          
        
          
          
          
            "payment_transactions": [
              
                "amount",
              
            ],
          
        
          
          
          
        
          
          
          
            "investments": [
              
                "amount_committed",
              
                "amount_funded",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "webhook_deliveries": [
              
                "http_status",
              
                "attempt_count",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "csv_jobs": [
              
                "total_rows",
              
                "processed_rows",
              
                "error_rows",
              
            ],
          
        
      };

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