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

          
            "companies": [
              
                "name",
              
                "short_name",
              
                "legal_name",
              
                "handelsregister_number",
              
                "register_court",
              
                "managing_directors",
              
                "vat_number",
              
                "tax_number",
              
                "eori_number",
              
                "gln_number",
              
                "scac",
              
                "address_line1",
              
                "address_line2",
              
                "postal_code",
              
                "city",
              
                "state",
              
                "country_code",
              
                "email",
              
                "phone",
              
                "website",
              
                "dispatch_email",
              
                "accounting_email",
              
                "hr_email",
              
                "invoice_prefix",
              
                "payroll_provider",
              
                "payroll_contact_email",
              
                "notes",
              
            ],
          
        
          
          

          
            "company_locations": [
              
                "name",
              
                "address_line1",
              
                "address_line2",
              
                "postal_code",
              
                "city",
              
                "state",
              
                "country_code",
              
                "phone",
              
                "email",
              
                "notes",
              
            ],
          
        
          
          

          
            "company_contacts": [
              
                "name",
              
                "title",
              
                "email",
              
                "phone",
              
                "mobile",
              
                "notes",
              
            ],
          
        
          
          

          
            "company_bank_accounts": [
              
                "bank_name",
              
                "iban",
              
                "bic",
              
                "account_holder",
              
            ],
          
        
          
          

          
            "company_permits": [
              
                "number",
              
                "issuer",
              
                "country_code",
              
                "notes",
              
            ],
          
        
          
          

          
            "company_insurances": [
              
                "provider",
              
                "policy_number",
              
                "broker",
              
                "contact_name",
              
                "contact_email",
              
                "contact_phone",
              
                "notes",
              
            ],
          
        
          
          

          
            "company_documents": [
              
                "title",
              
                "notes",
              
            ],
          
        
          
          

          
            "company_document_versions": [
              
                "number",
              
                "notes",
              
            ],
          
        
          
          

          
            "employees": [
              
                "first_name",
              
                "middle_name",
              
                "last_name",
              
                "national_id",
              
                "nationality",
              
                "email",
              
                "phone",
              
                "phone2",
              
                "permanent_address",
              
                "current_address",
              
                "emergency_contact",
              
                "emergency_phone",
              
                "notes",
              
            ],
          
        
          
          

          
            "employee_assignments": [
              
                "title",
              
                "notes",
              
            ],
          
        
          
          

          
            "employee_hr_records": [
              
                "contract_number",
              
                "position",
              
                "work_schedule",
              
                "bank_account_iban",
              
                "bank_name",
              
                "insurance_number",
              
                "tax_number",
              
                "tax_category",
              
                "termination_reason",
              
            ],
          
        
          
          

          
            "driver_profiles": [
              
                "driver_notes",
              
            ],
          
        
          
          

          
            "driver_compliances": [
              
                "license_country",
              
                "license_number",
              
                "license_restrictions",
              
                "cpc_number",
              
                "cpc_center",
              
                "cpc_type",
              
                "adr_number",
              
                "adr_restrictions",
              
                "medical_cert_number",
              
                "medical_issued_by",
              
                "psych_test_number",
              
                "medical_restrictions",
              
                "tacho_card_number",
              
                "tacho_country",
              
            ],
          
        
          
          

          
            "incidents": [
              
                "currency",
              
                "description",
              
                "location",
              
                "severity",
              
                "reported_by",
              
            ],
          
        
          
          

          
            "documents": [
              
                "title",
              
                "notes",
              
            ],
          
        
          
          

          
            "document_versions": [
              
                "number",
              
                "country",
              
                "notes",
              
            ],
          
        
          
          

          
        
          
          

          
            "customers": [
              
                "name",
              
                "legal_name",
              
                "tax_number",
              
                "vat_number",
              
                "eori_number",
              
                "email",
              
                "phone",
              
                "phone2",
              
                "website",
              
                "address_line1",
              
                "address_line2",
              
                "postal_code",
              
                "city",
              
                "country_code",
              
                "contact_person",
              
                "contact_email",
              
                "contact_phone",
              
                "notes",
              
            ],
          
        
          
          

          
            "vendors": [
              
                "name",
              
                "legal_name",
              
                "tax_number",
              
                "vat_number",
              
                "iban",
              
                "bank_name",
              
                "email",
              
                "phone",
              
                "phone2",
              
                "website",
              
                "address_line1",
              
                "address_line2",
              
                "postal_code",
              
                "city",
              
                "country_code",
              
                "contact_person",
              
                "contact_email",
              
                "contact_phone",
              
                "contract_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "vehicles": [
              
                "plate_number",
              
                "vin",
              
                "brand",
              
                "model",
              
                "variant",
              
                "tachograph_serial",
              
                "toll_obu_serial",
              
                "toll_contract_no",
              
                "insurance_notes",
              
                "notes",
              
            ],
          
        
          
          

          
            "trailers": [
              
                "plate_number",
              
                "vin",
              
                "brand",
              
                "model",
              
                "notes",
              
            ],
          
        
          
          

          
            "vehicle_trailer_links": [
              
                "notes",
              
            ],
          
        
          
          

          
            "vehicle_inspections": [
              
                "issuer",
              
                "report_no",
              
                "notes",
              
            ],
          
        
          
          

          
            "vehicle_maintenances": [
              
                "title",
              
                "workshop_name",
              
                "workshop_contact",
              
                "notes",
              
            ],
          
        
          
          

          
            "vehicle_insurances": [
              
                "provider",
              
                "policy_number",
              
                "broker",
              
                "notes",
              
            ],
          
        
          
          

          
            "vehicle_documents": [
              
                "title",
              
                "notes",
              
            ],
          
        
          
          

          
            "vehicle_document_versions": [
              
                "number",
              
                "notes",
              
            ],
          
        
          
          

          
            "driver_vehicle_assignments": [
              
                "notes",
              
            ],
          
        
          
          

          
            "orders": [
              
                "order_no",
              
                "reference",
              
                "title",
              
                "notes",
              
            ],
          
        
          
          

          
            "loads": [
              
                "load_no",
              
                "reference",
              
                "cargo_description",
              
                "cmr_number",
              
                "notes",
              
            ],
          
        
          
          

          
            "load_stops": [
              
                "name",
              
                "address_line1",
              
                "address_line2",
              
                "postal_code",
              
                "city",
              
                "state",
              
                "country_code",
              
                "contact_name",
              
                "contact_phone",
              
                "contact_email",
              
                "instructions",
              
                "reference_no",
              
                "notes",
              
            ],
          
        
          
          

          
            "trips": [
              
                "trip_no",
              
                "notes",
              
            ],
          
        
          
          

          
        
          
          

          
            "pod_files": [
              
                "file_key",
              
                "file_name",
              
                "mime_type",
              
                "file_url",
              
                "checksum_sha256",
              
                "uploaded_by",
              
                "notes",
              
            ],
          
        
          
          

          
            "invoices": [
              
                "invoice_no",
              
                "notes",
              
            ],
          
        
          
          

          
            "invoice_lines": [
              
                "description",
              
            ],
          
        
          
          

          
            "payments": [
              
                "reference",
              
                "notes",
              
            ],
          
        
          
          

          
            "cost_items": [
              
                "vendor",
              
                "reference",
              
                "notes",
              
            ],
          
        
          
          

          
            "cost_files": [
              
                "file_key",
              
                "file_name",
              
                "mime_type",
              
                "file_url",
              
                "checksum_sha256",
              
                "uploaded_by",
              
            ],
          
        
          
          

          
            "fuel_entries": [
              
                "station_name",
              
                "station_country_code",
              
            ],
          
        
          
          

          
            "toll_entries": [
              
                "toll_ref",
              
                "route_hint",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
            "companies": [
              
                "invoice_next_number",
              
                "payment_terms_days",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "company_insurances": [
              
                "coverage_amount",
              
            ],
          
        
          
          
          
        
          
          
          
            "company_document_versions": [
              
                "version_no",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "employee_hr_records": [
              
                "probation_days",
              
                "salary",
              
                "daily_allowance",
              
                "bonuses",
              
                "deductions",
              
                "vacation_days",
              
                "used_vacation_days",
              
            ],
          
        
          
          
          
        
          
          
          
            "driver_compliances": [
              
                "violations_count",
              
                "warnings_count",
              
            ],
          
        
          
          
          
            "incidents": [
              
                "amount",
              
                "points",
              
            ],
          
        
          
          
          
        
          
          
          
            "document_versions": [
              
                "version_no",
              
            ],
          
        
          
          
          
            "document_retention_policies": [
              
                "keep_min_versions",
              
                "keep_files_days",
              
                "keep_version_days",
              
            ],
          
        
          
          
          
            "customers": [
              
                "payment_terms_days",
              
                "credit_limit_eur",
              
            ],
          
        
          
          
          
        
          
          
          
            "vehicles": [
              
                "year",
              
                "gross_weight_kg",
              
                "curb_weight_kg",
              
                "payload_kg",
              
                "axle_count",
              
            ],
          
        
          
          
          
            "trailers": [
              
                "year",
              
                "gross_weight_kg",
              
                "curb_weight_kg",
              
                "payload_kg",
              
                "axle_count",
              
            ],
          
        
          
          
          
        
          
          
          
            "vehicle_inspections": [
              
                "odometer_km",
              
            ],
          
        
          
          
          
            "vehicle_maintenances": [
              
                "odometer_km",
              
                "cost_amount",
              
            ],
          
        
          
          
          
            "vehicle_insurances": [
              
                "coverage_amount",
              
            ],
          
        
          
          
          
        
          
          
          
            "vehicle_document_versions": [
              
                "version_no",
              
            ],
          
        
          
          
          
        
          
          
          
            "orders": [
              
                "agreed_price",
              
                "payment_terms_days",
              
            ],
          
        
          
          
          
            "loads": [
              
                "weight_kg",
              
                "volume_m3",
              
                "pallets",
              
                "pieces",
              
                "temperature_min_c",
              
                "temperature_max_c",
              
            ],
          
        
          
          
          
            "load_stops": [
              
                "sequence",
              
            ],
          
        
          
          
          
            "trips": [
              
                "start_odometer_km",
              
                "end_odometer_km",
              
                "distance_km",
              
            ],
          
        
          
          
          
            "trip_loads": [
              
                "sequence",
              
            ],
          
        
          
          
          
            "pod_files": [
              
                "size_bytes",
              
            ],
          
        
          
          
          
            "invoices": [
              
                "subtotal",
              
                "vat_rate",
              
                "vat_amount",
              
                "total",
              
            ],
          
        
          
          
          
            "invoice_lines": [
              
                "quantity",
              
                "unit_price",
              
                "amount",
              
            ],
          
        
          
          
          
            "payments": [
              
                "amount",
              
            ],
          
        
          
          
          
            "cost_items": [
              
                "amount",
              
            ],
          
        
          
          
          
            "cost_files": [
              
                "size_bytes",
              
            ],
          
        
          
          
          
            "fuel_entries": [
              
                "liters",
              
                "price_per_unit",
              
                "odometer_km",
              
            ],
          
        
          
          
          
        
      };

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