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, organizationsId, globalAccess) {
    try {
      if (!searchQuery) {
        throw new ValidationError('iam.errors.searchQueryRequired');
      }
      const tableColumns = {
        
          
          

          
            "users": [
              
                "firstName",
              
                "lastName",
              
                "phoneNumber",
              
                "email",
              
            ],
          
        
          
          
          
          

          
            "organizations": [
              
                "name",
              
            ],
          
        
          
          

          
            "tenants": [
              
                "name",
              
                "subdomain",
              
                "tagline",
              
                "primary_color",
              
                "timezone",
              
                "secondary_currencies",
              
                "address",
              
                "phone",
              
                "billing_email",
              
                "support_email",
              
                "ip_whitelist",
              
                "business_hours",
              
            ],
          
        
          
          

          
            "service_lines": [
              
                "name_fr",
              
                "name_en",
              
                "description_fr",
              
                "description_en",
              
                "typical_timeline",
              
            ],
          
        
          
          

          
            "services": [
              
                "name_fr",
              
                "name_en",
              
                "description_fr",
              
                "description_en",
              
                "deliverables",
              
                "required_skills",
              
            ],
          
        
          
          

          
            "companies": [
              
                "legal_name",
              
                "trade_name",
              
                "rccm",
              
                "tax_id",
              
                "industry",
              
                "website",
              
                "address",
              
                "city",
              
                "country",
              
                "notes",
              
            ],
          
        
          
          

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

          
            "tags": [
              
                "name",
              
                "color",
              
            ],
          
        
          
          

          
            "pipelines": [
              
                "name",
              
            ],
          
        
          
          

          
            "deal_stages": [
              
                "name",
              
            ],
          
        
          
          

          
            "leads": [
              
                "full_name",
              
                "email",
              
                "phone",
              
                "company_name",
              
                "message",
              
            ],
          
        
          
          

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

          
            "project_templates": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "projects": [
              
                "name",
              
                "code",
              
                "summary",
              
            ],
          
        
          
          

          
            "milestones": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
            "tasks": [
              
                "title",
              
                "description",
              
            ],
          
        
          
          

          
        
          
          

          
            "deliverables": [
              
                "name",
              
                "description",
              
                "client_feedback",
              
            ],
          
        
          
          

          
            "project_risks": [
              
                "title",
              
                "description",
              
                "mitigation_plan",
              
            ],
          
        
          
          

          
            "project_status_reports": [
              
                "accomplishments",
              
                "next_steps",
              
                "risks_issues",
              
                "client_notes",
              
            ],
          
        
          
          

          
            "skills": [
              
                "name",
              
            ],
          
        
          
          

          
            "team_members": [
              
                "notes",
              
            ],
          
        
          
          

          
        
          
          

          
            "resource_allocations": [
              
                "notes",
              
            ],
          
        
          
          

          
            "leave_requests": [
              
                "reason",
              
            ],
          
        
          
          

          
            "public_holidays": [
              
                "name",
              
                "country",
              
            ],
          
        
          
          

          
            "timesheets": [
              
                "approval_notes",
              
            ],
          
        
          
          

          
            "time_entries": [
              
                "description",
              
            ],
          
        
          
          

          
            "products": [
              
                "name",
              
                "sku",
              
                "description",
              
            ],
          
        
          
          

          
            "contracts": [
              
                "name",
              
                "notes",
              
            ],
          
        
          
          

          
            "invoices": [
              
                "invoice_number",
              
                "public_notes",
              
                "internal_notes",
              
            ],
          
        
          
          

          
            "invoice_line_items": [
              
                "description",
              
            ],
          
        
          
          

          
            "payments": [
              
                "provider_reference",
              
                "notes",
              
            ],
          
        
          
          

          
            "support_slas": [
              
                "name",
              
            ],
          
        
          
          

          
            "support_tickets": [
              
                "ticket_number",
              
                "subject",
              
                "description",
              
            ],
          
        
          
          

          
            "ticket_comments": [
              
                "body",
              
            ],
          
        
          
          

          
            "csat_surveys": [
              
                "feedback",
              
            ],
          
        
          
          

          
            "email_templates": [
              
                "name",
              
                "subject_fr",
              
                "subject_en",
              
                "body_fr",
              
                "body_en",
              
            ],
          
        
          
          

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

          
            "audit_logs": [
              
                "entity",
              
                "entity_key",
              
                "ip_address",
              
                "user_agent",
              
                "details",
              
            ],
          
        
          
          

          
            "imports": [
              
                "error_report",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
            "service_lines": [
              
                "min_price",
              
                "max_price",
              
            ],
          
        
          
          
          
            "services": [
              
                "min_price",
              
                "max_price",
              
                "typical_duration_weeks",
              
            ],
          
        
          
          
          
            "companies": [
              
                "annual_revenue",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "pipelines": [
              
                "sort_order",
              
            ],
          
        
          
          
          
            "deal_stages": [
              
                "probability_percent",
              
                "sort_order",
              
            ],
          
        
          
          
          
            "leads": [
              
                "score",
              
            ],
          
        
          
          
          
            "deals": [
              
                "amount",
              
            ],
          
        
          
          
          
            "project_templates": [
              
                "default_duration_weeks",
              
                "default_budget",
              
            ],
          
        
          
          
          
            "projects": [
              
                "budget_amount",
              
                "external_costs",
              
                "estimated_hours",
              
                "actual_hours",
              
            ],
          
        
          
          
          
            "milestones": [
              
                "sort_order",
              
            ],
          
        
          
          
          
            "tasks": [
              
                "estimated_hours",
              
                "actual_hours",
              
                "sort_order",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "team_members": [
              
                "hourly_rate",
              
                "weekly_capacity_hours",
              
            ],
          
        
          
          
          
        
          
          
          
            "resource_allocations": [
              
                "allocated_hours",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "time_entries": [
              
                "duration_hours",
              
            ],
          
        
          
          
          
            "products": [
              
                "unit_price",
              
            ],
          
        
          
          
          
            "contracts": [
              
                "amount",
              
                "renewal_notice_days",
              
            ],
          
        
          
          
          
            "invoices": [
              
                "subtotal",
              
                "tax_rate_percent",
              
                "tax_amount",
              
                "total",
              
                "amount_paid",
              
            ],
          
        
          
          
          
            "invoice_line_items": [
              
                "quantity",
              
                "unit_price",
              
                "line_total",
              
            ],
          
        
          
          
          
            "payments": [
              
                "amount",
              
            ],
          
        
          
          
          
            "support_slas": [
              
                "first_response_minutes",
              
                "resolution_minutes",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "csat_surveys": [
              
                "score",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "imports": [
              
                "total_rows",
              
                "success_rows",
              
                "failed_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' && organizationsId) {
            whereCondition.organizationsId = organizationsId;
          }
          

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