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

          
            "companies": [
              
                "name",
              
                "legal_name",
              
                "tax_number",
              
                "industry",
              
                "website",
              
                "phone",
              
                "email",
              
                "billing_address",
              
                "shipping_address",
              
            ],
          
        
          
          

          
            "contacts": [
              
                "first_name",
              
                "last_name",
              
                "email",
              
                "phone",
              
                "job_title",
              
                "notes",
              
            ],
          
        
          
          

          
            "pipelines": [
              
                "name",
              
            ],
          
        
          
          

          
            "pipeline_stages": [
              
                "name",
              
            ],
          
        
          
          

          
            "leads": [
              
                "title",
              
                "description",
              
            ],
          
        
          
          

          
            "deals": [
              
                "name",
              
                "notes",
              
            ],
          
        
          
          

          
            "activities": [
              
                "subject",
              
                "details",
              
            ],
          
        
          
          

          
            "materials": [
              
                "sku",
              
                "name",
              
                "unit_of_measure",
              
                "specification",
              
            ],
          
        
          
          

          
            "warehouses": [
              
                "name",
              
                "code",
              
                "address",
              
            ],
          
        
          
          

          
            "inventory_items": [
              
                "lot_number",
              
                "serial_number",
              
                "location_bin",
              
            ],
          
        
          
          

          
            "machines": [
              
                "name",
              
                "code",
              
                "notes",
              
            ],
          
        
          
          

          
            "production_orders": [
              
                "order_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "production_operations": [
              
                "name",
              
                "work_instructions",
              
            ],
          
        
          
          

          
            "quality_inspections": [
              
                "inspection_number",
              
                "findings",
              
            ],
          
        
          
          

          
            "nonconformances": [
              
                "ncr_number",
              
                "description",
              
                "root_cause",
              
                "corrective_action",
              
            ],
          
        
          
          

          
            "vendors": [
              
                "name",
              
                "email",
              
                "phone",
              
                "website",
              
                "address",
              
                "notes",
              
            ],
          
        
          
          

          
            "venues": [
              
                "name",
              
                "address",
              
                "city",
              
                "country",
              
                "contact_name",
              
                "contact_phone",
              
                "contact_email",
              
                "notes",
              
            ],
          
        
          
          

          
            "events": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "event_tasks": [
              
                "title",
              
                "details",
              
            ],
          
        
          
          

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

          
            "event_schedule_items": [
              
                "title",
              
                "location",
              
                "description",
              
            ],
          
        
          
          

          
            "budget_items": [
              
                "name",
              
                "notes",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "pipeline_stages": [
              
                "sort_order",
              
            ],
          
        
          
          
          
            "leads": [
              
                "estimated_value",
              
            ],
          
        
          
          
          
            "deals": [
              
                "amount",
              
                "probability",
              
            ],
          
        
          
          
          
        
          
          
          
            "materials": [
              
                "standard_cost",
              
                "reorder_point",
              
                "reorder_quantity",
              
            ],
          
        
          
          
          
        
          
          
          
            "inventory_items": [
              
                "quantity_on_hand",
              
                "quantity_reserved",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "production_operations": [
              
                "sequence",
              
                "planned_quantity",
              
                "good_quantity",
              
                "scrap_quantity",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "venues": [
              
                "capacity",
              
            ],
          
        
          
          
          
            "events": [
              
                "budget_total",
              
                "budget_spent",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "budget_items": [
              
                "estimated_cost",
              
                "actual_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}%` }
                )
              )),
            ],
          };

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