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

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

          
            "job_positions": [
              
                "code",
              
                "name",
              
            ],
          
        
          
          

          
            "employees": [
              
                "employee_code",
              
                "full_name",
              
                "phone",
              
                "nik",
              
                "npwp",
              
                "bank_name",
              
                "bank_account_number",
              
                "bank_account_name",
              
            ],
          
        
          
          

          
            "employee_contracts": [
              
                "notes",
              
            ],
          
        
          
          

          
            "attendance_logs": [
              
                "remarks",
              
            ],
          
        
          
          

          
            "attendance_requests": [
              
                "reason",
              
            ],
          
        
          
          

          
            "overtime_logs": [
              
                "reason",
              
            ],
          
        
          
          

          
            "disciplinary_actions": [
              
                "description",
              
            ],
          
        
          
          

          
            "kpi_periods": [
              
                "name",
              
            ],
          
        
          
          

          
            "kpi_scores": [
              
                "notes",
              
            ],
          
        
          
          

          
            "outlet_revenues": [
              
                "notes",
              
            ],
          
        
          
          

          
            "service_charge_pools": [
              
                "period_name",
              
                "notes",
              
            ],
          
        
          
          

          
            "loan_accounts": [
              
                "notes",
              
            ],
          
        
          
          

          
            "payroll_periods": [
              
                "name",
              
            ],
          
        
          
          

          
            "payroll_items": [
              
                "adjustment_notes",
              
            ],
          
        
          
          

          
            "payroll_adjustments": [
              
                "description",
              
            ],
          
        
          
          

          
            "payslips": [
              
                "slip_number",
              
                "delivery_notes",
              
            ],
          
        
          
          

          
            "notification_messages": [
              
                "recipient",
              
                "subject",
              
                "body",
              
                "provider_message_id",
              
                "error_message",
              
            ],
          
        
          
          

          
            "audit_logs": [
              
                "action",
              
                "entity_name",
              
                "entity_key",
              
                "before_data",
              
                "after_data",
              
                "ip_address",
              
                "user_agent",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
            "outlets": [
              
                "gps_lat",
              
                "gps_lng",
              
                "gps_radius_m",
              
            ],
          
        
          
          
          
            "job_positions": [
              
                "payroll_weight",
              
            ],
          
        
          
          
          
            "employees": [
              
                "base_salary_monthly",
              
                "position_allowance_fixed",
              
                "meal_allowance_daily",
              
                "transport_allowance_daily",
              
            ],
          
        
          
          
          
        
          
          
          
            "attendance_logs": [
              
                "check_in_lat",
              
                "check_in_lng",
              
                "check_out_lat",
              
                "check_out_lng",
              
                "late_minutes",
              
            ],
          
        
          
          
          
        
          
          
          
            "overtime_logs": [
              
                "hours",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "kpi_scores": [
              
                "absensi_score",
              
                "disiplin_score",
              
                "produktif_score",
              
                "attitude_score",
              
                "sop_score",
              
                "final_score",
              
            ],
          
        
          
          
          
            "outlet_revenues": [
              
                "gross_revenue",
              
                "net_revenue",
              
            ],
          
        
          
          
          
            "service_charge_pools": [
              
                "total_amount",
              
            ],
          
        
          
          
          
            "loan_accounts": [
              
                "principal_amount",
              
                "installment_amount",
              
                "remaining_amount",
              
            ],
          
        
          
          
          
            "payroll_periods": [
              
                "standard_workdays",
              
            ],
          
        
          
          
          
            "payroll_items": [
              
                "workdays",
              
                "sick_days",
              
                "leave_days",
              
                "absent_days",
              
                "late_count",
              
                "late_minutes_total",
              
                "base_salary_monthly",
              
                "daily_rate",
              
                "base_salary_total",
              
                "meal_transport_total",
              
                "position_allowance_total",
              
                "kpi_score",
              
                "kpi_allowance_total",
              
                "overtime_hours_total",
              
                "overtime_rate",
              
                "overtime_total",
              
                "revenue_bonus_total",
              
                "service_charge_total",
              
                "deduction_total",
              
                "take_home_pay",
              
            ],
          
        
          
          
          
            "payroll_adjustments": [
              
                "amount",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
      };

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