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

          
            "world_regions": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "locations": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "player_profiles": [
              
                "first_name",
              
                "last_name",
              
            ],
          
        
          
          

          
            "customization_items": [
              
                "name",
              
            ],
          
        
          
          

          
            "tools": [
              
                "name",
              
            ],
          
        
          
          

          
            "item_categories": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "items": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "npcs": [
              
                "name",
              
                "bio",
              
            ],
          
        
          
          

          
            "families": [
              
                "name",
              
                "family_story",
              
            ],
          
        
          
          

          
        
          
          

          
        
          
          

          
            "dialogue_topics": [
              
                "title",
              
                "summary",
              
            ],
          
        
          
          

          
            "dialogue_lines": [
              
                "line_text",
              
            ],
          
        
          
          

          
            "quests": [
              
                "title",
              
                "description",
              
            ],
          
        
          
          

          
        
          
          

          
            "market_stores": [
              
                "name",
              
                "store_note",
              
            ],
          
        
          
          

          
        
          
          

          
            "suppliers": [
              
                "name",
              
                "contact_details",
              
            ],
          
        
          
          

          
        
          
          

          
        
          
          

          
            "purchase_orders": [
              
                "notes",
              
            ],
          
        
          
          

          
        
          
          

          
            "deliveries": [
              
                "delivery_note",
              
            ],
          
        
          
          

          
            "shelves": [
              
                "name",
              
            ],
          
        
          
          

          
        
          
          

          
            "cash_registers": [
              
                "name",
              
            ],
          
        
          
          

          
        
          
          

          
        
          
          

          
            "daily_reports": [
              
                "notes",
              
            ],
          
        
          
          

          
            "weather_states": [
              
                "name",
              
            ],
          
        
          
          

          
        
          
          

          
            "price_modifiers": [
              
                "notes",
              
            ],
          
        
          
          

          
            "crops": [
              
                "name",
              
            ],
          
        
          
          

          
            "farm_plots": [
              
                "name",
              
            ],
          
        
          
          

          
        
          
          

          
            "fish_species": [
              
                "name",
              
            ],
          
        
          
          

          
            "fishing_spots": [
              
                "name",
              
            ],
          
        
          
          

          
        
          
          

          
            "crafting_recipes": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
        
          
          

          
            "buildings": [
              
                "name",
              
            ],
          
        
          
          

          
            "construction_projects": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "festivals": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
        
          
          

          
            "random_events": [
              
                "title",
              
                "description",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
            "world_regions": [
              
                "latitude",
              
                "longitude",
              
            ],
          
        
          
          
          
            "locations": [
              
                "latitude",
              
                "longitude",
              
            ],
          
        
          
          
          
            "player_profiles": [
              
                "level",
              
                "experience_points",
              
                "money_balance",
              
                "pix_balance",
              
                "reputation_score",
              
            ],
          
        
          
          
          
            "customization_items": [
              
                "price",
              
            ],
          
        
          
          
          
            "tools": [
              
                "durability_max",
              
                "durability_current",
              
                "repair_cost",
              
            ],
          
        
          
          
          
        
          
          
          
            "items": [
              
                "base_price",
              
                "weight",
              
                "max_stack_size",
              
                "shelf_life_days",
              
            ],
          
        
          
          
          
            "npcs": [
              
                "age",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "npc_relationships": [
              
                "friendship_points",
              
                "trust_points",
              
            ],
          
        
          
          
          
        
          
          
          
            "dialogue_lines": [
              
                "priority",
              
            ],
          
        
          
          
          
            "quests": [
              
                "reward_money",
              
                "reward_reputation",
              
            ],
          
        
          
          
          
            "quest_objectives": [
              
                "target_quantity",
              
                "sequence_order",
              
            ],
          
        
          
          
          
            "market_stores": [
              
                "cash_balance",
              
                "pix_balance",
              
                "card_balance",
              
            ],
          
        
          
          
          
            "employees": [
              
                "daily_wage",
              
            ],
          
        
          
          
          
            "suppliers": [
              
                "reliability_score",
              
            ],
          
        
          
          
          
            "store_products": [
              
                "current_price",
              
                "reorder_point",
              
                "target_stock",
              
                "tax_rate",
              
            ],
          
        
          
          
          
            "store_inventory_batches": [
              
                "quantity_on_hand",
              
                "unit_cost",
              
            ],
          
        
          
          
          
            "purchase_orders": [
              
                "subtotal_amount",
              
                "tax_amount",
              
                "total_amount",
              
            ],
          
        
          
          
          
            "purchase_order_lines": [
              
                "quantity_ordered",
              
                "unit_cost",
              
                "line_total",
              
            ],
          
        
          
          
          
        
          
          
          
            "shelves": [
              
                "capacity_units",
              
            ],
          
        
          
          
          
            "shelf_slots": [
              
                "facings",
              
                "max_quantity",
              
                "current_quantity",
              
                "slot_index",
              
            ],
          
        
          
          
          
            "cash_registers": [
              
                "cash_drawer_balance",
              
            ],
          
        
          
          
          
            "sales_transactions": [
              
                "subtotal_amount",
              
                "tax_amount",
              
                "total_amount",
              
            ],
          
        
          
          
          
            "sales_transaction_lines": [
              
                "quantity",
              
                "unit_price",
              
                "line_total",
              
            ],
          
        
          
          
          
            "daily_reports": [
              
                "gross_sales",
              
                "net_sales",
              
                "transactions_count",
              
                "cash_total",
              
                "pix_total",
              
                "card_total",
              
                "wages_paid",
              
                "inventory_purchases",
              
            ],
          
        
          
          
          
            "weather_states": [
              
                "temperature_c",
              
                "wind_speed",
              
                "rain_intensity",
              
            ],
          
        
          
          
          
            "world_calendar_days": [
              
                "tourism_index",
              
                "inflation_index",
              
            ],
          
        
          
          
          
            "price_modifiers": [
              
                "multiplier",
              
            ],
          
        
          
          
          
            "crops": [
              
                "growth_days",
              
                "regrowth_days",
              
                "water_per_day",
              
            ],
          
        
          
          
          
            "farm_plots": [
              
                "width_tiles",
              
                "height_tiles",
              
            ],
          
        
          
          
          
            "plantings": [
              
                "quantity_planted",
              
                "watered_today",
              
            ],
          
        
          
          
          
            "fish_species": [
              
                "base_bite_rate",
              
            ],
          
        
          
          
          
            "fishing_spots": [
              
                "difficulty_rating",
              
            ],
          
        
          
          
          
            "fishing_catches": [
              
                "weight",
              
                "length",
              
            ],
          
        
          
          
          
            "crafting_recipes": [
              
                "output_quantity",
              
                "craft_time_seconds",
              
            ],
          
        
          
          
          
            "recipe_ingredients": [
              
                "quantity",
              
            ],
          
        
          
          
          
            "buildings": [
              
                "upgrade_level",
              
            ],
          
        
          
          
          
            "construction_projects": [
              
                "budget_cost",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
      };

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