                three_ds_decision_manager_config: None,
                card_testing_guard_config: None,
                card_testing_secret_key: None,
                is_clear_pan_retries_enabled: None,
                is_debit_routing_enabled: None,
                merchant_business_country: None,
                revenue_recovery_retry_algorithm_type: None,
                revenue_recovery_retry_algorithm_data: None,
                is_iframe_redirection_enabled: None,
                is_external_vault_enabled: None,
                external_vault_connector_details: None,
                merchant_category_code: None,
                merchant_country_code: None,
                split_txns_enabled: None,
                billing_processor_id: None,
            },
            ProfileUpdate::ExtendedCardInfoUpdate {
                is_extended_card_info_enabled,
            } => Self {
                profile_name: None,
                modified_at: now,
                return_url: None,
                enable_payment_response_hash: None,
                payment_response_hash_key: None,
                redirect_to_merchant_with_http_post: None,
                webhook_details: None,
                metadata: None,
                is_recon_enabled: None,
                applepay_verified_domains: None,
                payment_link_config: None,
                session_expiry: None,
                authentication_connector_details: None,
                payout_link_config: None,
                is_extended_card_info_enabled: Some(is_extended_card_info_enabled),
                extended_card_info_config: None,
                is_connector_agnostic_mit_enabled: None,
                use_billing_as_payment_method_billing: None,
                collect_shipping_details_from_wallet_connector: None,
                collect_billing_details_from_wallet_connector: None,
                outgoing_webhook_custom_http_headers: None,
                always_collect_billing_details_from_wallet_connector: None,
                always_collect_shipping_details_from_wallet_connector: None,
                routing_algorithm_id: None,
                payout_routing_algorithm_id: None,
                order_fulfillment_time: None,
                order_fulfillment_time_origin: None,
                frm_routing_algorithm_id: None,
                default_fallback_routing: None,
                should_collect_cvv_during_payment: None,
                tax_connector_id: None,
                is_tax_connector_enabled: None,
                is_network_tokenization_enabled: None,
                is_auto_retries_enabled: None,
                max_auto_retries_enabled: None,
                is_click_to_pay_enabled: None,
                authentication_product_ids: None,
                three_ds_decision_manager_config: None,
                card_testing_guard_config: None,
                card_testing_secret_key: None,
                is_clear_pan_retries_enabled: None,
                is_debit_routing_enabled: None,
                merchant_business_country: None,
                revenue_recovery_retry_algorithm_type: None,
                revenue_recovery_retry_algorithm_data: None,
                is_iframe_redirection_enabled: None,
                is_external_vault_enabled: None,
                external_vault_connector_details: None,
                merchant_category_code: None,
                merchant_country_code: None,
                split_txns_enabled: None,
                billing_processor_id: None,
            },
            ProfileUpdate::ConnectorAgnosticMitUpdate {
                is_connector_agnostic_mit_enabled,
            } => Self {
                profile_name: None,
                modified_at: now,
                return_url: None,
                enable_payment_response_hash: None,
                payment_response_hash_key: None,
                redirect_to_merchant_with_http_post: None,
                webhook_details: None,
                metadata: None,
                is_recon_enabled: None,
                applepay_verified_domains: None,
                payment_link_config: None,
                session_expiry: None,
                authentication_connector_details: None,
                payout_link_config: None,
                is_extended_card_info_enabled: None,
                extended_card_info_config: None,
                is_connector_agnostic_mit_enabled: Some(is_connector_agnostic_mit_enabled),
                use_billing_as_payment_method_billing: None,
                collect_shipping_details_from_wallet_connector: None,
                collect_billing_details_from_wallet_connector: None,
                outgoing_webhook_custom_http_headers: None,
                always_collect_billing_details_from_wallet_connector: None,
                always_collect_shipping_details_from_wallet_connector: None,
                routing_algorithm_id: None,
                payout_routing_algorithm_id: None,
                order_fulfillment_time: None,
                order_fulfillment_time_origin: None,
                frm_routing_algorithm_id: None,
                default_fallback_routing: None,
                should_collect_cvv_during_payment: None,
                tax_connector_id: None,
                is_tax_connector_enabled: None,
                is_network_tokenization_enabled: None,
                is_auto_retries_enabled: None,
                max_auto_retries_enabled: None,
                is_click_to_pay_enabled: None,
                authentication_product_ids: None,
                three_ds_decision_manager_config: None,
                card_testing_guard_config: None,
                card_testing_secret_key: None,
                is_clear_pan_retries_enabled: None,
                is_debit_routing_enabled: None,
                merchant_business_country: None,
                revenue_recovery_retry_algorithm_type: None,
                revenue_recovery_retry_algorithm_data: None,
                is_iframe_redirection_enabled: None,
                is_external_vault_enabled: None,
                external_vault_connector_details: None,
                merchant_category_code: None,
                merchant_country_code: None,
                split_txns_enabled: None,
                billing_processor_id: None,
            },
            ProfileUpdate::DefaultRoutingFallbackUpdate {
                default_fallback_routing,
            } => Self {
                profile_name: None,
                modified_at: now,
                return_url: None,
                enable_payment_response_hash: None,
                payment_response_hash_key: None,
                redirect_to_merchant_with_http_post: None,
                webhook_details: None,
                metadata: None,
                is_recon_enabled: None,
                applepay_verified_domains: None,
                payment_link_config: None,
                session_expiry: None,
                authentication_connector_details: None,
                payout_link_config: None,
                is_extended_card_info_enabled: None,
                extended_card_info_config: None,
                is_connector_agnostic_mit_enabled: None,
                use_billing_as_payment_method_billing: None,
                collect_shipping_details_from_wallet_connector: None,
                collect_billing_details_from_wallet_connector: None,
                outgoing_webhook_custom_http_headers: None,
                always_collect_billing_details_from_wallet_connector: None,
                always_collect_shipping_details_from_wallet_connector: None,
                routing_algorithm_id: None,
                payout_routing_algorithm_id: None,
                order_fulfillment_time: None,
                order_fulfillment_time_origin: None,
                frm_routing_algorithm_id: None,
                default_fallback_routing,
                should_collect_cvv_during_payment: None,
                tax_connector_id: None,
                is_tax_connector_enabled: None,
                is_network_tokenization_enabled: None,
                is_auto_retries_enabled: None,
                max_auto_retries_enabled: None,
                is_click_to_pay_enabled: None,
                authentication_product_ids: None,
                three_ds_decision_manager_config: None,
                card_testing_guard_config: None,
                card_testing_secret_key: None,
                is_clear_pan_retries_enabled: None,
                is_debit_routing_enabled: None,
                merchant_business_country: None,
                revenue_recovery_retry_algorithm_type: None,
                revenue_recovery_retry_algorithm_data: None,
                is_iframe_redirection_enabled: None,
                is_external_vault_enabled: None,
                external_vault_connector_details: None,
                merchant_category_code: None,
                merchant_country_code: None,
                split_txns_enabled: None,
                billing_processor_id: None,
            },
            ProfileUpdate::NetworkTokenizationUpdate {
                is_network_tokenization_enabled,
            } => Self {
                profile_name: None,
                modified_at: now,
                return_url: None,
                enable_payment_response_hash: None,
                payment_response_hash_key: None,
                redirect_to_merchant_with_http_post: None,
                webhook_details: None,
                metadata: None,
                is_recon_enabled: None,
                applepay_verified_domains: None,
                payment_link_config: None,
                session_expiry: None,
                authentication_connector_details: None,
                payout_link_config: None,
                is_extended_card_info_enabled: None,
                extended_card_info_config: None,
                is_connector_agnostic_mit_enabled: None,
                use_billing_as_payment_method_billing: None,
                collect_shipping_details_from_wallet_connector: None,
                collect_billing_details_from_wallet_connector: None,
                outgoing_webhook_custom_http_headers: None,
                always_collect_billing_details_from_wallet_connector: None,
                always_collect_shipping_details_from_wallet_connector: None,
                routing_algorithm_id: None,
                payout_routing_algorithm_id: None,
                order_fulfillment_time: None,
                order_fulfillment_time_origin: None,
                frm_routing_algorithm_id: None,
                default_fallback_routing: None,
                should_collect_cvv_during_payment: None,
                tax_connector_id: None,
                is_tax_connector_enabled: None,
                is_network_tokenization_enabled: Some(is_network_tokenization_enabled),
                is_auto_retries_enabled: None,
                max_auto_retries_enabled: None,
                is_click_to_pay_enabled: None,
                authentication_product_ids: None,
                three_ds_decision_manager_config: None,
                card_testing_guard_config: None,
                card_testing_secret_key: None,
                is_clear_pan_retries_enabled: None,
                is_debit_routing_enabled: None,
                merchant_business_country: None,
                revenue_recovery_retry_algorithm_type: None,
                revenue_recovery_retry_algorithm_data: None,
                is_iframe_redirection_enabled: None,
                is_external_vault_enabled: None,
                external_vault_connector_details: None,
                merchant_category_code: None,
                merchant_country_code: None,
                split_txns_enabled: None,
                billing_processor_id: None,
            },
            ProfileUpdate::CollectCvvDuringPaymentUpdate {
                should_collect_cvv_during_payment,
            } => Self {
                profile_name: None,
                modified_at: now,
                return_url: None,
                enable_payment_response_hash: None,
                payment_response_hash_key: None,
                redirect_to_merchant_with_http_post: None,
                webhook_details: None,
                metadata: None,
                is_recon_enabled: None,
                applepay_verified_domains: None,
                payment_link_config: None,
                session_expiry: None,
                authentication_connector_details: None,
                payout_link_config: None,
                is_extended_card_info_enabled: None,
                extended_card_info_config: None,
                is_connector_agnostic_mit_enabled: None,
                use_billing_as_payment_method_billing: None,
                collect_shipping_details_from_wallet_connector: None,
                collect_billing_details_from_wallet_connector: None,
                outgoing_webhook_custom_http_headers: None,
                always_collect_billing_details_from_wallet_connector: None,
                always_collect_shipping_details_from_wallet_connector: None,
                routing_algorithm_id: None,
                payout_routing_algorithm_id: None,
                order_fulfillment_time: None,
                order_fulfillment_time_origin: None,
                frm_routing_algorithm_id: None,
                default_fallback_routing: None,
                should_collect_cvv_during_payment: Some(should_collect_cvv_during_payment),
                tax_connector_id: None,
                is_tax_connector_enabled: None,
                is_network_tokenization_enabled: None,
                is_auto_retries_enabled: None,
                max_auto_retries_enabled: None,
                is_click_to_pay_enabled: None,
                authentication_product_ids: None,
                three_ds_decision_manager_config: None,
                card_testing_guard_config: None,
                card_testing_secret_key: None,
                is_clear_pan_retries_enabled: None,
                is_debit_routing_enabled: None,
                merchant_business_country: None,
                revenue_recovery_retry_algorithm_type: None,
                revenue_recovery_retry_algorithm_data: None,
                is_iframe_redirection_enabled: None,
                is_external_vault_enabled: None,
                external_vault_connector_details: None,
                merchant_category_code: None,
                merchant_country_code: None,
                split_txns_enabled: None,
                billing_processor_id: None,
            },
            ProfileUpdate::DecisionManagerRecordUpdate {
                three_ds_decision_manager_config,
            } => Self {
                profile_name: None,
                modified_at: now,
                return_url: None,
                enable_payment_response_hash: None,
                payment_response_hash_key: None,
                redirect_to_merchant_with_http_post: None,
                webhook_details: None,
                metadata: None,
                is_recon_enabled: None,
                applepay_verified_domains: None,
                payment_link_config: None,
                session_expiry: None,
                authentication_connector_details: None,
                payout_link_config: None,
                is_extended_card_info_enabled: None,
                extended_card_info_config: None,
                is_connector_agnostic_mit_enabled: None,
                use_billing_as_payment_method_billing: None,
                collect_shipping_details_from_wallet_connector: None,
                collect_billing_details_from_wallet_connector: None,
                outgoing_webhook_custom_http_headers: None,
                always_collect_billing_details_from_wallet_connector: None,
                always_collect_shipping_details_from_wallet_connector: None,
                routing_algorithm_id: None,
                payout_routing_algorithm_id: None,
                order_fulfillment_time: None,
                order_fulfillment_time_origin: None,
                frm_routing_algorithm_id: None,
                default_fallback_routing: None,
                should_collect_cvv_during_payment: None,
                tax_connector_id: None,
                is_tax_connector_enabled: None,
                is_network_tokenization_enabled: None,
                is_auto_retries_enabled: None,
                max_auto_retries_enabled: None,
                is_click_to_pay_enabled: None,
                authentication_product_ids: None,
                three_ds_decision_manager_config: Some(three_ds_decision_manager_config),
                card_testing_guard_config: None,
                card_testing_secret_key: None,
                is_clear_pan_retries_enabled: None,
                is_debit_routing_enabled: None,
                merchant_business_country: None,
                revenue_recovery_retry_algorithm_type: None,
                revenue_recovery_retry_algorithm_data: None,
                is_iframe_redirection_enabled: None,
                is_external_vault_enabled: None,
                external_vault_connector_details: None,
                merchant_category_code: None,
                merchant_country_code: None,
                split_txns_enabled: None,
                billing_processor_id: None,
            },
            ProfileUpdate::CardTestingSecretKeyUpdate {
                card_testing_secret_key,
            } => Self {
                profile_name: None,
                modified_at: now,
                return_url: None,
                enable_payment_response_hash: None,
                payment_response_hash_key: None,
                redirect_to_merchant_with_http_post: None,
                webhook_details: None,
                metadata: None,
                is_recon_enabled: None,
                applepay_verified_domains: None,
                payment_link_config: None,
                session_expiry: None,
                authentication_connector_details: None,
                payout_link_config: None,
                is_extended_card_info_enabled: None,
                extended_card_info_config: None,
                is_connector_agnostic_mit_enabled: None,
                use_billing_as_payment_method_billing: None,
                collect_shipping_details_from_wallet_connector: None,
                collect_billing_details_from_wallet_connector: None,
                outgoing_webhook_custom_http_headers: None,
                always_collect_billing_details_from_wallet_connector: None,
                always_collect_shipping_details_from_wallet_connector: None,
                routing_algorithm_id: None,
                payout_routing_algorithm_id: None,
                order_fulfillment_time: None,
                order_fulfillment_time_origin: None,
                frm_routing_algorithm_id: None,
                default_fallback_routing: None,
                should_collect_cvv_during_payment: None,
                tax_connector_id: None,
                is_tax_connector_enabled: None,
                is_network_tokenization_enabled: None,
                is_auto_retries_enabled: None,
                max_auto_retries_enabled: None,
                is_click_to_pay_enabled: None,
                authentication_product_ids: None,
                three_ds_decision_manager_config: None,
                card_testing_guard_config: None,
                card_testing_secret_key: card_testing_secret_key.map(Encryption::from),
                is_clear_pan_retries_enabled: None,
                is_debit_routing_enabled: None,
                merchant_business_country: None,
                revenue_recovery_retry_algorithm_type: None,
                revenue_recovery_retry_algorithm_data: None,
                is_iframe_redirection_enabled: None,
                is_external_vault_enabled: None,
                external_vault_connector_details: None,
                merchant_category_code: None,
                merchant_country_code: None,
                split_txns_enabled: None,
                billing_processor_id: None,
            },
            ProfileUpdate::RevenueRecoveryAlgorithmUpdate {
                revenue_recovery_retry_algorithm_type,
                revenue_recovery_retry_algorithm_data,
            } => Self {
                profile_name: None,
                modified_at: now,
                return_url: None,
                enable_payment_response_hash: None,
                payment_response_hash_key: None,
                redirect_to_merchant_with_http_post: None,
                webhook_details: None,
                metadata: None,
                is_recon_enabled: None,
                applepay_verified_domains: None,
                payment_link_config: None,
                session_expiry: None,
                authentication_connector_details: None,
                payout_link_config: None,
                is_extended_card_info_enabled: None,
                extended_card_info_config: None,
                is_connector_agnostic_mit_enabled: None,
                use_billing_as_payment_method_billing: None,
                collect_shipping_details_from_wallet_connector: None,
                collect_billing_details_from_wallet_connector: None,
                outgoing_webhook_custom_http_headers: None,
                always_collect_billing_details_from_wallet_connector: None,
                always_collect_shipping_details_from_wallet_connector: None,
                routing_algorithm_id: None,
                payout_routing_algorithm_id: None,
                order_fulfillment_time: None,
                order_fulfillment_time_origin: None,
                frm_routing_algorithm_id: None,
                default_fallback_routing: None,
                should_collect_cvv_during_payment: None,
                tax_connector_id: None,
                is_tax_connector_enabled: None,
                is_network_tokenization_enabled: None,
                is_auto_retries_enabled: None,
                max_auto_retries_enabled: None,
                is_click_to_pay_enabled: None,
                authentication_product_ids: None,
                three_ds_decision_manager_config: None,
                card_testing_guard_config: None,
                card_testing_secret_key: None,
                is_clear_pan_retries_enabled: None,
                is_debit_routing_enabled: None,
                merchant_business_country: None,
                revenue_recovery_retry_algorithm_type: Some(revenue_recovery_retry_algorithm_type),
                revenue_recovery_retry_algorithm_data,
                is_iframe_redirection_enabled: None,
                is_external_vault_enabled: None,
                external_vault_connector_details: None,
                merchant_category_code: None,
                merchant_country_code: None,
                split_txns_enabled: None,
                billing_processor_id: None,
            },
        }
    }
}

#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl super::behaviour::Conversion for Profile {
    type DstType = diesel_models::business_profile::Profile;
    type NewDstType = diesel_models::business_profile::ProfileNew;

    async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
        Ok(diesel_models::business_profile::Profile {
            id: self.id,
            merchant_id: self.merchant_id,
            profile_name: self.profile_name,
            created_at: self.created_at,
            modified_at: self.modified_at,
            return_url: self.return_url,
            enable_payment_response_hash: self.enable_payment_response_hash,
            payment_response_hash_key: self.payment_response_hash_key,
            redirect_to_merchant_with_http_post: self.redirect_to_merchant_with_http_post,
            webhook_details: self.webhook_details,
            metadata: self.metadata,
            is_recon_enabled: self.is_recon_enabled,
            applepay_verified_domains: self.applepay_verified_domains,
            payment_link_config: self.payment_link_config,
            session_expiry: self.session_expiry,
            authentication_connector_details: self.authentication_connector_details,
            payout_link_config: self.payout_link_config,
            is_extended_card_info_enabled: self.is_extended_card_info_enabled,
            extended_card_info_config: self.extended_card_info_config,
            is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled,
            use_billing_as_payment_method_billing: self.use_billing_as_payment_method_billing,
            collect_shipping_details_from_wallet_connector: self
                .collect_shipping_details_from_wallet_connector,
            collect_billing_details_from_wallet_connector: self
                .collect_billing_details_from_wallet_connector,
            outgoing_webhook_custom_http_headers: self
                .outgoing_webhook_custom_http_headers
                .map(Encryption::from),
            routing_algorithm_id: self.routing_algorithm_id,
            always_collect_billing_details_from_wallet_connector: self
                .always_collect_billing_details_from_wallet_connector,
            always_collect_shipping_details_from_wallet_connector: self
                .always_collect_shipping_details_from_wallet_connector,
            payout_routing_algorithm_id: self.payout_routing_algorithm_id,
            order_fulfillment_time: self.order_fulfillment_time,
            order_fulfillment_time_origin: self.order_fulfillment_time_origin,
            frm_routing_algorithm_id: self.frm_routing_algorithm_id,
            default_fallback_routing: self.default_fallback_routing,
            should_collect_cvv_during_payment: self.should_collect_cvv_during_payment,
            tax_connector_id: self.tax_connector_id,
            is_tax_connector_enabled: Some(self.is_tax_connector_enabled),
            version: self.version,
            dynamic_routing_algorithm: None,
            is_network_tokenization_enabled: self.is_network_tokenization_enabled,
            is_auto_retries_enabled: None,
            max_auto_retries_enabled: None,
            always_request_extended_authorization: None,
            is_click_to_pay_enabled: self.is_click_to_pay_enabled,
            authentication_product_ids: self.authentication_product_ids,
            three_ds_decision_manager_config: self.three_ds_decision_manager_config,
            card_testing_guard_config: self.card_testing_guard_config,
            card_testing_secret_key: self.card_testing_secret_key.map(|name| name.into()),
            is_clear_pan_retries_enabled: self.is_clear_pan_retries_enabled,
            force_3ds_challenge: None,
            is_debit_routing_enabled: self.is_debit_routing_enabled,
            merchant_business_country: self.merchant_business_country,
            revenue_recovery_retry_algorithm_type: self.revenue_recovery_retry_algorithm_type,
            revenue_recovery_retry_algorithm_data: self.revenue_recovery_retry_algorithm_data,
            is_iframe_redirection_enabled: self.is_iframe_redirection_enabled,
            is_external_vault_enabled: self.is_external_vault_enabled,
            external_vault_connector_details: self.external_vault_connector_details,
            three_ds_decision_rule_algorithm: None,
            acquirer_config_map: None,
            merchant_category_code: self.merchant_category_code,
            merchant_country_code: self.merchant_country_code,
            dispute_polling_interval: None,
            split_txns_enabled: Some(self.split_txns_enabled),
            is_manual_retry_enabled: None,
            always_enable_overcapture: None,
            billing_processor_id: self.billing_processor_id,
        })
    }

    async fn convert_back(
        state: &keymanager::KeyManagerState,
        item: Self::DstType,
        key: &Secret<Vec<u8>>,
        key_manager_identifier: keymanager::Identifier,
    ) -> CustomResult<Self, ValidationError>
    where
        Self: Sized,
    {
        async {
            Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {
                id: item.id,
                merchant_id: item.merchant_id,
                profile_name: item.profile_name,
                created_at: item.created_at,
                modified_at: item.modified_at,
                return_url: item.return_url,
                enable_payment_response_hash: item.enable_payment_response_hash,
                payment_response_hash_key: item.payment_response_hash_key,
                redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post,
                webhook_details: item.webhook_details,
                metadata: item.metadata,
                is_recon_enabled: item.is_recon_enabled,
                applepay_verified_domains: item.applepay_verified_domains,
                payment_link_config: item.payment_link_config,
                session_expiry: item.session_expiry,
                authentication_connector_details: item.authentication_connector_details,
                payout_link_config: item.payout_link_config,
                is_extended_card_info_enabled: item.is_extended_card_info_enabled,
                extended_card_info_config: item.extended_card_info_config,
                is_connector_agnostic_mit_enabled: item.is_connector_agnostic_mit_enabled,
                use_billing_as_payment_method_billing: item.use_billing_as_payment_method_billing,
                collect_shipping_details_from_wallet_connector: item
                    .collect_shipping_details_from_wallet_connector,
                collect_billing_details_from_wallet_connector: item
                    .collect_billing_details_from_wallet_connector,
                outgoing_webhook_custom_http_headers: item
                    .outgoing_webhook_custom_http_headers
                    .async_lift(|inner| async {
                        crypto_operation(
                            state,
                            type_name!(Self::DstType),
                            CryptoOperation::DecryptOptional(inner),
                            key_manager_identifier.clone(),
                            key.peek(),
                        )
                        .await
                        .and_then(|val| val.try_into_optionaloperation())
                    })
                    .await?,
                routing_algorithm_id: item.routing_algorithm_id,
                always_collect_billing_details_from_wallet_connector: item
                    .always_collect_billing_details_from_wallet_connector,
                always_collect_shipping_details_from_wallet_connector: item
                    .always_collect_shipping_details_from_wallet_connector,
                order_fulfillment_time: item.order_fulfillment_time,
                order_fulfillment_time_origin: item.order_fulfillment_time_origin,
                frm_routing_algorithm_id: item.frm_routing_algorithm_id,
                payout_routing_algorithm_id: item.payout_routing_algorithm_id,
                default_fallback_routing: item.default_fallback_routing,
                should_collect_cvv_during_payment: item.should_collect_cvv_during_payment,
                tax_connector_id: item.tax_connector_id,
                is_tax_connector_enabled: item.is_tax_connector_enabled.unwrap_or(false),
                version: item.version,
                is_network_tokenization_enabled: item.is_network_tokenization_enabled,
                is_click_to_pay_enabled: item.is_click_to_pay_enabled,
                authentication_product_ids: item.authentication_product_ids,
                three_ds_decision_manager_config: item.three_ds_decision_manager_config,
                card_testing_guard_config: item.card_testing_guard_config,
                card_testing_secret_key: match item.card_testing_secret_key {
                    Some(encrypted_value) => crypto_operation(
                        state,
                        type_name!(Self::DstType),
                        CryptoOperation::DecryptOptional(Some(encrypted_value)),
                        key_manager_identifier.clone(),
                        key.peek(),
                    )
                    .await
                    .and_then(|val| val.try_into_optionaloperation())
                    .unwrap_or_default(),
                    None => None,
                },
                is_clear_pan_retries_enabled: item.is_clear_pan_retries_enabled,
                is_debit_routing_enabled: item.is_debit_routing_enabled,
                merchant_business_country: item.merchant_business_country,
                revenue_recovery_retry_algorithm_type: item.revenue_recovery_retry_algorithm_type,
                revenue_recovery_retry_algorithm_data: item.revenue_recovery_retry_algorithm_data,
                is_iframe_redirection_enabled: item.is_iframe_redirection_enabled,
                is_external_vault_enabled: item.is_external_vault_enabled,
                external_vault_connector_details: item.external_vault_connector_details,
                merchant_category_code: item.merchant_category_code,
                merchant_country_code: item.merchant_country_code,
                split_txns_enabled: item.split_txns_enabled.unwrap_or_default(),
                billing_processor_id: item.billing_processor_id,
            })
        }
        .await
        .change_context(ValidationError::InvalidValue {
            message: "Failed while decrypting business profile data".to_string(),
        })
    }

    async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
        Ok(diesel_models::business_profile::ProfileNew {
            id: self.id,
            merchant_id: self.merchant_id,
            profile_name: self.profile_name,
            created_at: self.created_at,
            modified_at: self.modified_at,
            return_url: self.return_url,
            enable_payment_response_hash: self.enable_payment_response_hash,
            payment_response_hash_key: self.payment_response_hash_key,
            redirect_to_merchant_with_http_post: self.redirect_to_merchant_with_http_post,
            webhook_details: self.webhook_details,
            metadata: self.metadata,
            is_recon_enabled: self.is_recon_enabled,
            applepay_verified_domains: self.applepay_verified_domains,
            payment_link_config: self.payment_link_config,
            session_expiry: self.session_expiry,
            authentication_connector_details: self.authentication_connector_details,
            payout_link_config: self.payout_link_config,
            is_extended_card_info_enabled: self.is_extended_card_info_enabled,
            extended_card_info_config: self.extended_card_info_config,
            is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled,
            use_billing_as_payment_method_billing: self.use_billing_as_payment_method_billing,
            collect_shipping_details_from_wallet_connector: self
                .collect_shipping_details_from_wallet_connector,
            collect_billing_details_from_wallet_connector: self
                .collect_billing_details_from_wallet_connector,
            outgoing_webhook_custom_http_headers: self
                .outgoing_webhook_custom_http_headers
                .map(Encryption::from),
            routing_algorithm_id: self.routing_algorithm_id,
            always_collect_billing_details_from_wallet_connector: self
                .always_collect_billing_details_from_wallet_connector,
            always_collect_shipping_details_from_wallet_connector: self
                .always_collect_shipping_details_from_wallet_connector,
            order_fulfillment_time: self.order_fulfillment_time,
            order_fulfillment_time_origin: self.order_fulfillment_time_origin,
            frm_routing_algorithm_id: self.frm_routing_algorithm_id,
            payout_routing_algorithm_id: self.payout_routing_algorithm_id,
            default_fallback_routing: self.default_fallback_routing,
            should_collect_cvv_during_payment: self.should_collect_cvv_during_payment,
            tax_connector_id: self.tax_connector_id,
            is_tax_connector_enabled: Some(self.is_tax_connector_enabled),
            version: self.version,
            is_network_tokenization_enabled: self.is_network_tokenization_enabled,
            is_auto_retries_enabled: None,
            max_auto_retries_enabled: None,
            is_click_to_pay_enabled: self.is_click_to_pay_enabled,
            authentication_product_ids: self.authentication_product_ids,
            three_ds_decision_manager_config: self.three_ds_decision_manager_config,
            card_testing_guard_config: self.card_testing_guard_config,
            card_testing_secret_key: self.card_testing_secret_key.map(Encryption::from),
            is_clear_pan_retries_enabled: Some(self.is_clear_pan_retries_enabled),
            is_debit_routing_enabled: self.is_debit_routing_enabled,
            merchant_business_country: self.merchant_business_country,
            revenue_recovery_retry_algorithm_type: self.revenue_recovery_retry_algorithm_type,
            revenue_recovery_retry_algorithm_data: self.revenue_recovery_retry_algorithm_data,
            is_iframe_redirection_enabled: self.is_iframe_redirection_enabled,
            is_external_vault_enabled: self.is_external_vault_enabled,
            external_vault_connector_details: self.external_vault_connector_details,
            merchant_category_code: self.merchant_category_code,
            merchant_country_code: self.merchant_country_code,
            split_txns_enabled: Some(self.split_txns_enabled),
            billing_processor_id: self.billing_processor_id,
        })
    }
}


// Implementation: impl FlowMetric for for AnalyticsFlow
// File: crates/analytics/src/lib.rs
// Module: analytics
// Methods: 0 total (0 public)

impl FlowMetric for for AnalyticsFlow


// Function: upsert_decision_manager_config
// File: crates/router/src/routes/routing.rs
// Module: router

pub fn upsert_decision_manager_config(
    state: web::Data<AppState>,
    req: HttpRequest,
    json_payload: web::Json<api_models::conditional_configs::DecisionManager>,
) -> impl Responder


// Module Structure
// File: crates/router/src/types/api/verify_connector.rs
// Module: router

// Public submodules:
pub mod paypal;
pub mod stripe;


// Implementation: impl Responder
// File: crates/router/src/routes/routing.rs
// Module: router
// Methods: 0 total (0 public)

impl Responder


// File: crates/euclid/src/dssa/truth.rs
// Module: euclid

use std::sync::LazyLock;

use euclid_macros::knowledge;

use crate::{dssa::graph::euclid_graph_prelude, frontend::dir};

pub static ANALYSIS_GRAPH: LazyLock<hyperswitch_constraint_graph::ConstraintGraph<dir::DirValue>> =
    LazyLock::new(|| {
        knowledge! {
            // Payment Method should be `Card` for a CardType to be present
            PaymentMethod(Card) ->> CardType(any);

            // Payment Method should be `PayLater` for a PayLaterType to be present
            PaymentMethod(PayLater) ->> PayLaterType(any);

            // Payment Method should be `Wallet` for a WalletType to be present
            PaymentMethod(Wallet) ->> WalletType(any);

            // Payment Method should be `BankRedirect` for a BankRedirectType to
            // be present
            PaymentMethod(BankRedirect) ->> BankRedirectType(any);

            // Payment Method should be `BankTransfer` for a BankTransferType to
            // be present
            PaymentMethod(BankTransfer) ->> BankTransferType(any);

            // Payment Method should be `GiftCard` for a GiftCardType to
            // be present
            PaymentMethod(GiftCard) ->> GiftCardType(any);

            // Payment Method should be `RealTimePayment` for a RealTimePaymentType to
            // be present
            PaymentMethod(RealTimePayment) ->> RealTimePaymentType(any);
        }
    });


// Struct: GrpcHeaders
// File: crates/external_services/src/grpc_client.rs
// Module: external_services
// Implementations: 0

pub struct GrpcHeaders


// Function: insert_user_and_merchant_in_db
// File: crates/router/src/types/domain/user.rs
// Module: router

pub fn insert_user_and_merchant_in_db(
        &self,
        state: SessionState,
    ) -> UserResult<UserFromStorage>


// Struct: IdealData
// File: crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct IdealData


// Struct: WorldpayPaymentsRequest
// File: crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct WorldpayPaymentsRequest


// Struct: FlexitiPaymentsRequest
// File: crates/hyperswitch_connectors/src/connectors/flexiti/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct FlexitiPaymentsRequest


// Implementation: impl KafkaDispute
// File: crates/router/src/services/kafka/dispute.rs
// Module: router
// Methods: 1 total (1 public)

impl KafkaDispute


// Function: inner
// File: crates/test_utils/src/connector_auth.rs
// Module: test_utils

pub fn inner(&self) -> &HashMap<String, ConnectorAuthType>


// Struct: NetworkTokenDataForVault
// File: crates/hyperswitch_domain_models/src/payments.rs
// Module: hyperswitch_domain_models
// Implementations: 0

pub struct NetworkTokenDataForVault


// Struct: RefundUpdateRequest
// File: crates/api_models/src/refunds.rs
// Module: api_models
// Implementations: 0

pub struct RefundUpdateRequest


// Function: make_card_network_tokenization_request
// File: crates/router/src/core/payment_methods/network_tokenization.rs
// Module: router

pub fn make_card_network_tokenization_request(
    state: &routes::SessionState,
    card: &api_payment_methods::CardDetail,
    customer_id: &id_type::GlobalCustomerId,
) -> CustomResult<(NetworkTokenDetails, String), errors::NetworkTokenizationError>


// Function: perform_fallback_routing
// File: crates/router/src/core/payments/routing.rs
// Module: router

pub fn perform_fallback_routing(
    state: &SessionState,
    key_store: &domain::MerchantKeyStore,
    transaction_data: &routing::TransactionData<'_>,
    eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>,
    business_profile: &domain::Profile,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>>


// Implementation: impl api::PaymentSession for for Trustpayments
// File: crates/hyperswitch_connectors/src/connectors/trustpayments.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl api::PaymentSession for for Trustpayments


// Struct: SubscriptionEstimateResponse
// File: crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct SubscriptionEstimateResponse


// Implementation: impl EphemeralKey
// File: crates/router/src/routes/app.rs
// Module: router
// Methods: 1 total (1 public)

impl EphemeralKey


// Implementation: impl ConnectorSpecifications for for Trustpay
// File: crates/hyperswitch_connectors/src/connectors/trustpay.rs
// Module: hyperswitch_connectors
// Methods: 4 total (0 public)

impl ConnectorSpecifications for for Trustpay


// Struct: ZenWebhookSignature
// File: crates/hyperswitch_connectors/src/connectors/zen/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct ZenWebhookSignature


// Struct: DeleteTokenizeDataWorkflow
// File: crates/router/src/workflows/tokenized_data.rs
// Module: router
// Implementations: 0

pub struct DeleteTokenizeDataWorkflow


// Struct: ErrorDetails
// File: crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
// Module: hyperswitch_domain_models
// Implementations: 0

pub struct ErrorDetails


// Struct: GlobalPayRouterData
// File: crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct GlobalPayRouterData<T>


// File: crates/router/tests/connectors/silverflow.rs
// Module: router

use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData};
use masking::Secret;
use router::types::{self, api, storage::enums};
use test_utils::connector_auth;

use crate::utils::{self, ConnectorActions};

#[derive(Clone, Copy)]
struct SilverflowTest;
impl ConnectorActions for SilverflowTest {}
impl utils::Connector for SilverflowTest {
    fn get_data(&self) -> api::ConnectorData {
        use router::connector::Silverflow;
        utils::construct_connector_data_old(
            Box::new(Silverflow::new()),
            types::Connector::Plaid,
            api::GetToken::Connector,
            None,
        )
    }

    fn get_auth_token(&self) -> types::ConnectorAuthType {
        utils::to_connector_auth_type(
            connector_auth::ConnectorAuthentication::new()
                .silverflow
                .expect("Missing connector authentication configuration")
                .into(),
        )
    }

    fn get_name(&self) -> String {
        "silverflow".to_string()
    }
}

static CONNECTOR: SilverflowTest = SilverflowTest {};

fn get_default_payment_info() -> Option<utils::PaymentInfo> {
    None
}

fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
    None
}

// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
    let response = CONNECTOR
        .authorize_payment(payment_method_details(), get_default_payment_info())
        .await
        .expect("Authorize payment response");
    assert_eq!(response.status, enums::AttemptStatus::Authorized);
}

// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
    let response = CONNECTOR
        .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
        .await
        .expect("Capture payment response");
    assert_eq!(response.status, enums::AttemptStatus::Charged);
}

// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
    let response = CONNECTOR
        .authorize_and_capture_payment(
            payment_method_details(),
            Some(types::PaymentsCaptureData {
                amount_to_capture: 50,
                ..utils::PaymentCaptureType::default().0
            }),
            get_default_payment_info(),
        )
        .await
        .expect("Capture payment response");
    assert_eq!(response.status, enums::AttemptStatus::Charged);
}

// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
    let authorize_response = CONNECTOR
        .authorize_payment(payment_method_details(), get_default_payment_info())
        .await
        .expect("Authorize payment response");
    let txn_id = utils::get_connector_transaction_id(authorize_response.response);
    let response = CONNECTOR
        .psync_retry_till_status_matches(
            enums::AttemptStatus::Authorized,
            Some(types::PaymentsSyncData {
                connector_transaction_id: types::ResponseId::ConnectorTransactionId(
                    txn_id.unwrap(),
                ),
                ..Default::default()
            }),
            get_default_payment_info(),
        )
        .await
        .expect("PSync response");
    assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}

// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
    let response = CONNECTOR
        .authorize_and_void_payment(
            payment_method_details(),
            Some(types::PaymentsCancelData {
                connector_transaction_id: String::from(""),
                cancellation_reason: Some("requested_by_customer".to_string()),
                ..Default::default()
            }),
            get_default_payment_info(),
        )
        .await
        .expect("Void payment response");
    assert_eq!(response.status, enums::AttemptStatus::Voided);
}

// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
    let response = CONNECTOR
        .capture_payment_and_refund(
            payment_method_details(),
            None,
            None,
            get_default_payment_info(),
        )
        .await
        .unwrap();
    assert_eq!(
        response.response.unwrap().refund_status,
        enums::RefundStatus::Success,
    );
}

// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
    let response = CONNECTOR
        .capture_payment_and_refund(
            payment_method_details(),
            None,
            Some(types::RefundsData {
                refund_amount: 50,
                ..utils::PaymentRefundType::default().0
            }),
            get_default_payment_info(),
        )
        .await
        .unwrap();
    assert_eq!(
        response.response.unwrap().refund_status,
        enums::RefundStatus::Success,
    );
}

// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
    let refund_response = CONNECTOR
        .capture_payment_and_refund(
            payment_method_details(),
            None,
            None,
            get_default_payment_info(),
        )
        .await
        .unwrap();
    let response = CONNECTOR
        .rsync_retry_till_status_matches(
            enums::RefundStatus::Success,
            refund_response.response.unwrap().connector_refund_id,
            None,
            get_default_payment_info(),
        )
        .await
        .unwrap();
    assert_eq!(
        response.response.unwrap().refund_status,
        enums::RefundStatus::Success,
    );
}

// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
    let authorize_response = CONNECTOR
        .make_payment(payment_method_details(), get_default_payment_info())
        .await
        .unwrap();
    assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}

// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
    let authorize_response = CONNECTOR
        .make_payment(payment_method_details(), get_default_payment_info())
        .await
        .unwrap();
    assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
    let txn_id = utils::get_connector_transaction_id(authorize_response.response);
    assert_ne!(txn_id, None, "Empty connector transaction id");
    let response = CONNECTOR
        .psync_retry_till_status_matches(
            enums::AttemptStatus::Charged,
            Some(types::PaymentsSyncData {
                connector_transaction_id: types::ResponseId::ConnectorTransactionId(
                    txn_id.unwrap(),
                ),
                capture_method: Some(enums::CaptureMethod::Automatic),
                ..Default::default()
            }),
            get_default_payment_info(),
        )
        .await
        .unwrap();
    assert_eq!(response.status, enums::AttemptStatus::Charged,);
}

// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
    let response = CONNECTOR
        .make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
        .await
        .unwrap();
    assert_eq!(
        response.response.unwrap().refund_status,
        enums::RefundStatus::Success,
    );
}

// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
    let refund_response = CONNECTOR
        .make_payment_and_refund(
            payment_method_details(),
            Some(types::RefundsData {
                refund_amount: 50,
                ..utils::PaymentRefundType::default().0
            }),
            get_default_payment_info(),
        )
        .await
        .unwrap();
    assert_eq!(
        refund_response.response.unwrap().refund_status,
        enums::RefundStatus::Success,
    );
}

// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
    CONNECTOR
        .make_payment_and_multiple_refund(
            payment_method_details(),
            Some(types::RefundsData {
                refund_amount: 50,
                ..utils::PaymentRefundType::default().0
            }),
            get_default_payment_info(),
        )
        .await;
}

// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
    let refund_response = CONNECTOR
        .make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
        .await
        .unwrap();
    let response = CONNECTOR
        .rsync_retry_till_status_matches(
            enums::RefundStatus::Success,
            refund_response.response.unwrap().connector_refund_id,
            None,
            get_default_payment_info(),
        )
        .await
        .unwrap();
    assert_eq!(
        response.response.unwrap().refund_status,
        enums::RefundStatus::Success,
    );
}

// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
    let response = CONNECTOR
        .make_payment(
            Some(types::PaymentsAuthorizeData {
                payment_method_data: PaymentMethodData::Card(Card {
                    card_cvc: Secret::new("12345".to_string()),
                    ..utils::CCardType::default().0
                }),
                ..utils::PaymentAuthorizeType::default().0
            }),
            get_default_payment_info(),
        )
        .await
        .unwrap();
    assert_eq!(
        response.response.unwrap_err().message,
        "Your card's security code is invalid.".to_string(),
    );
}

// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
    let response = CONNECTOR
        .make_payment(
            Some(types::PaymentsAuthorizeData {
                payment_method_data: PaymentMethodData::Card(Card {
                    card_exp_month: Secret::new("20".to_string()),
                    ..utils::CCardType::default().0
                }),
                ..utils::PaymentAuthorizeType::default().0
            }),
            get_default_payment_info(),
        )
        .await
        .unwrap();
    assert_eq!(
        response.response.unwrap_err().message,
        "Your card's expiration month is invalid.".to_string(),
    );
}

// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
    let response = CONNECTOR
        .make_payment(
            Some(types::PaymentsAuthorizeData {
                payment_method_data: PaymentMethodData::Card(Card {
                    card_exp_year: Secret::new("2000".to_string()),
                    ..utils::CCardType::default().0
                }),
                ..utils::PaymentAuthorizeType::default().0
            }),
            get_default_payment_info(),
        )
        .await
        .unwrap();
    assert_eq!(
        response.response.unwrap_err().message,
        "Your card's expiration year is invalid.".to_string(),
    );
}

// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
    let authorize_response = CONNECTOR
        .make_payment(payment_method_details(), get_default_payment_info())
        .await
        .unwrap();
    assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
    let txn_id = utils::get_connector_transaction_id(authorize_response.response);
    assert_ne!(txn_id, None, "Empty connector transaction id");
    let void_response = CONNECTOR
        .void_payment(txn_id.unwrap(), None, get_default_payment_info())
        .await
        .unwrap();
    assert_eq!(
        void_response.response.unwrap_err().message,
        "You cannot cancel this PaymentIntent because it has a status of succeeded."
    );
}

// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
    let capture_response = CONNECTOR
        .capture_payment("123456789".to_string(), None, get_default_payment_info())
        .await
        .unwrap();
    assert_eq!(
        capture_response.response.unwrap_err().message,
        String::from("No such payment_intent: '123456789'")
    );
}

// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
    let response = CONNECTOR
        .make_payment_and_refund(
            payment_method_details(),
            Some(types::RefundsData {
                refund_amount: 150,
                ..utils::PaymentRefundType::default().0
            }),
            get_default_payment_info(),
        )
        .await
        .unwrap();
    assert_eq!(
        response.response.unwrap_err().message,
        "Refund amount (₹1.50) is greater than charge amount (₹1.00)",
    );
}

// Connector dependent test cases goes here

// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests


// Function: payments_external_authentication
// File: crates/openapi/src/routes/payments.rs
// Module: openapi

pub fn payments_external_authentication()


// File: crates/drainer/src/query.rs
// Module: drainer

use std::sync::Arc;

use common_utils::errors::CustomResult;
use diesel_models::errors::DatabaseError;

use crate::{kv, logger, metrics, pg_connection, services::Store};

#[async_trait::async_trait]
pub trait ExecuteQuery {
    async fn execute_query(
        self,
        store: &Arc<Store>,
        pushed_at: i64,
    ) -> CustomResult<(), DatabaseError>;
}

#[async_trait::async_trait]
impl ExecuteQuery for kv::DBOperation {
    async fn execute_query(
        self,
        store: &Arc<Store>,
        pushed_at: i64,
    ) -> CustomResult<(), DatabaseError> {
        let conn = pg_connection(&store.master_pool).await;
        let operation = self.operation();
        let table = self.table();

        let tags = router_env::metric_attributes!(("operation", operation), ("table", table));

        let (result, execution_time) =
            Box::pin(common_utils::date_time::time_it(|| self.execute(&conn))).await;

        push_drainer_delay(pushed_at, operation, table, tags);
        metrics::QUERY_EXECUTION_TIME.record(execution_time, tags);

        match result {
            Ok(result) => {
                logger::info!(operation = operation, table = table, ?result);
                metrics::SUCCESSFUL_QUERY_EXECUTION.add(1, tags);
                Ok(())
            }
            Err(err) => {
                logger::error!(operation = operation, table = table, ?err);
                metrics::ERRORS_WHILE_QUERY_EXECUTION.add(1, tags);
                Err(err)
            }
        }
    }
}

#[inline(always)]
fn push_drainer_delay(
    pushed_at: i64,
    operation: &str,
    table: &str,
    tags: &[router_env::opentelemetry::KeyValue],
) {
    let drained_at = common_utils::date_time::now_unix_timestamp();
    let delay = drained_at - pushed_at;

    logger::debug!(operation, table, delay = format!("{delay} secs"));

    match u64::try_from(delay) {
        Ok(delay) => metrics::DRAINER_DELAY_SECONDS.record(delay, tags),
        Err(error) => logger::error!(
            pushed_at,
            drained_at,
            delay,
            ?error,
            "Invalid drainer delay"
        ),
    }
}


// Implementation: impl FraudCheckConnectorData
// File: crates/router/src/types/api/fraud_check.rs
// Module: router
// Methods: 2 total (1 public)

impl FraudCheckConnectorData


// Implementation: impl api::PaymentCapture for for Facilitapay
// File: crates/hyperswitch_connectors/src/connectors/facilitapay.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl api::PaymentCapture for for Facilitapay


// Struct: CybersourceSenderInfo
// File: crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct CybersourceSenderInfo


// File: crates/router/src/core/errors.rs
// Module: router
// Public functions: 1
// Public structs: 2

pub mod chat;
pub mod customers_error_response;
pub mod error_handlers;
pub mod transformers;
#[cfg(feature = "olap")]
pub mod user;
pub mod utils;

use std::fmt::Display;

pub use ::payment_methods::core::errors::VaultError;
use actix_web::{body::BoxBody, ResponseError};
pub use common_utils::errors::{CustomResult, ParsingError, ValidationError};
use diesel_models::errors as storage_errors;
pub use hyperswitch_domain_models::errors::api_error_response::{
    ApiErrorResponse, ErrorType, NotImplementedMessage,
};
pub use hyperswitch_interfaces::errors::ConnectorError;
pub use redis_interface::errors::RedisError;
use scheduler::errors as sch_errors;
use storage_impl::errors as storage_impl_errors;
#[cfg(feature = "olap")]
pub use user::*;

pub use self::{
    customers_error_response::CustomersErrorResponse,
    sch_errors::*,
    storage_errors::*,
    storage_impl_errors::*,
    utils::{ConnectorErrorExt, StorageErrorExt},
};
use crate::services;
pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>;
pub type RouterResponse<T> = CustomResult<services::ApplicationResponse<T>, ApiErrorResponse>;

pub type ApplicationResult<T> = error_stack::Result<T, ApplicationError>;
pub type ApplicationResponse<T> = ApplicationResult<services::ApplicationResponse<T>>;

pub type CustomerResponse<T> =
    CustomResult<services::ApplicationResponse<T>, CustomersErrorResponse>;

macro_rules! impl_error_display {
    ($st: ident, $arg: tt) => {
        impl Display for $st {
            fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(
                    fmt,
                    "{{ error_type: {:?}, error_description: {} }}",
                    self, $arg
                )
            }
        }
    };
}

#[macro_export]
macro_rules! capture_method_not_supported {
    ($connector:expr, $capture_method:expr) => {
        Err(errors::ConnectorError::NotSupported {
            message: format!("{} for selected payment method", $capture_method),
            connector: $connector,
        }
        .into())
    };
    ($connector:expr, $capture_method:expr, $payment_method_type:expr) => {
        Err(errors::ConnectorError::NotSupported {
            message: format!("{} for {}", $capture_method, $payment_method_type),
            connector: $connector,
        }
        .into())
    };
}

#[macro_export]
macro_rules! unimplemented_payment_method {
    ($payment_method:expr, $connector:expr) => {
        errors::ConnectorError::NotImplemented(format!(
            "{} through {}",
            $payment_method, $connector
        ))
    };
    ($payment_method:expr, $flow:expr, $connector:expr) => {
        errors::ConnectorError::NotImplemented(format!(
            "{} {} through {}",
            $payment_method, $flow, $connector
        ))
    };
}

macro_rules! impl_error_type {
    ($name: ident, $arg: tt) => {
        #[derive(Debug)]
        pub struct $name;

        impl_error_display!($name, $arg);

        impl std::error::Error for $name {}
    };
}

impl_error_type!(EncryptionError, "Encryption error");

impl From<ring::error::Unspecified> for EncryptionError {
    fn from(_: ring::error::Unspecified) -> Self {
        Self
    }
}

pub fn http_not_implemented() -> actix_web::HttpResponse<BoxBody> {
    ApiErrorResponse::NotImplemented {
        message: NotImplementedMessage::Default,
    }
    .error_response()
}

#[derive(Debug, thiserror::Error)]
pub enum HealthCheckOutGoing {
    #[error("Outgoing call failed with error: {message}")]
    OutGoingFailed { message: String },
}

#[derive(Debug, thiserror::Error)]
pub enum AwsKmsError {
    #[error("Failed to base64 decode input data")]
    Base64DecodingFailed,
    #[error("Failed to AWS KMS decrypt input data")]
    DecryptionFailed,
    #[error("Missing plaintext AWS KMS decryption output")]
    MissingPlaintextDecryptionOutput,
    #[error("Failed to UTF-8 decode decryption output")]
    Utf8DecodingFailed,
}

#[derive(Debug, thiserror::Error, serde::Serialize)]
pub enum WebhooksFlowError {
    #[error("Merchant webhook config not found")]
    MerchantConfigNotFound,
    #[error("Webhook details for merchant not configured")]
    MerchantWebhookDetailsNotFound,
    #[error("Merchant does not have a webhook URL configured")]
    MerchantWebhookUrlNotConfigured,
    #[error("Webhook event updation failed")]
    WebhookEventUpdationFailed,
    #[error("Outgoing webhook body signing failed")]
    OutgoingWebhookSigningFailed,
    #[error("Webhook api call to merchant failed")]
    CallToMerchantFailed,
    #[error("Webhook not received by merchant")]
    NotReceivedByMerchant,
    #[error("Dispute webhook status validation failed")]
    DisputeWebhookValidationFailed,
    #[error("Outgoing webhook body encoding failed")]
    OutgoingWebhookEncodingFailed,
    #[error("Failed to update outgoing webhook process tracker task")]
    OutgoingWebhookProcessTrackerTaskUpdateFailed,
    #[error("Failed to schedule retry attempt for outgoing webhook")]
    OutgoingWebhookRetrySchedulingFailed,
    #[error("Outgoing webhook response encoding failed")]
    OutgoingWebhookResponseEncodingFailed,
    #[error("ID generation failed")]
    IdGenerationFailed,
}

impl WebhooksFlowError {
    pub(crate) fn is_webhook_delivery_retryable_error(&self) -> bool {
        match self {
            Self::MerchantConfigNotFound
            | Self::MerchantWebhookDetailsNotFound
            | Self::MerchantWebhookUrlNotConfigured
            | Self::OutgoingWebhookResponseEncodingFailed => false,

            Self::WebhookEventUpdationFailed
            | Self::OutgoingWebhookSigningFailed
            | Self::CallToMerchantFailed
            | Self::NotReceivedByMerchant
            | Self::DisputeWebhookValidationFailed
            | Self::OutgoingWebhookEncodingFailed
            | Self::OutgoingWebhookProcessTrackerTaskUpdateFailed
            | Self::OutgoingWebhookRetrySchedulingFailed
            | Self::IdGenerationFailed => true,
        }
    }
}

#[derive(Debug, thiserror::Error)]
pub enum ApplePayDecryptionError {
    #[error("Failed to base64 decode input data")]
    Base64DecodingFailed,
    #[error("Failed to decrypt input data")]
    DecryptionFailed,
    #[error("Certificate parsing failed")]
    CertificateParsingFailed,
    #[error("Certificate parsing failed")]
    MissingMerchantId,
    #[error("Key Deserialization failure")]
    KeyDeserializationFailed,
    #[error("Failed to Derive a shared secret key")]
    DerivingSharedSecretKeyFailed,
}

#[derive(Debug, thiserror::Error)]
pub enum PazeDecryptionError {
    #[error("Failed to base64 decode input data")]
    Base64DecodingFailed,
    #[error("Failed to decrypt input data")]
    DecryptionFailed,
    #[error("Certificate parsing failed")]
    CertificateParsingFailed,
}

#[derive(Debug, thiserror::Error)]
pub enum GooglePayDecryptionError {
    #[error("Invalid expiration time")]
    InvalidExpirationTime,
    #[error("Failed to base64 decode input data")]
    Base64DecodingFailed,
    #[error("Failed to decrypt input data")]
    DecryptionFailed,
    #[error("Failed to deserialize input data")]
    DeserializationFailed,
    #[error("Certificate parsing failed")]
    CertificateParsingFailed,
    #[error("Key deserialization failure")]
    KeyDeserializationFailed,
    #[error("Failed to derive a shared ephemeral key")]
    DerivingSharedEphemeralKeyFailed,
    #[error("Failed to derive a shared secret key")]
    DerivingSharedSecretKeyFailed,
    #[error("Failed to parse the tag")]
    ParsingTagError,
    #[error("HMAC verification failed")]
    HmacVerificationFailed,
    #[error("Failed to derive Elliptic Curve key")]
    DerivingEcKeyFailed,
    #[error("Failed to Derive Public key")]
    DerivingPublicKeyFailed,
    #[error("Failed to Derive Elliptic Curve group")]
    DerivingEcGroupFailed,
    #[error("Failed to allocate memory for big number")]
    BigNumAllocationFailed,
    #[error("Failed to get the ECDSA signature")]
    EcdsaSignatureFailed,
    #[error("Failed to verify the signature")]
    SignatureVerificationFailed,
    #[error("Invalid signature is provided")]
    InvalidSignature,
    #[error("Failed to parse the Signed Key")]
    SignedKeyParsingFailure,
    #[error("The Signed Key is expired")]
    SignedKeyExpired,
    #[error("Failed to parse the ECDSA signature")]
    EcdsaSignatureParsingFailed,
    #[error("Invalid intermediate signature is provided")]
    InvalidIntermediateSignature,
    #[error("Invalid protocol version")]
    InvalidProtocolVersion,
    #[error("Decrypted Token has expired")]
    DecryptedTokenExpired,
    #[error("Failed to parse the given value")]
    ParsingFailed,
}

#[cfg(feature = "detailed_errors")]
pub mod error_stack_parsing {

    #[derive(serde::Deserialize)]
    pub struct NestedErrorStack<'a> {
        context: std::borrow::Cow<'a, str>,
        attachments: Vec<std::borrow::Cow<'a, str>>,
        sources: Vec<NestedErrorStack<'a>>,
    }

    #[derive(serde::Serialize, Debug)]
    struct LinearErrorStack<'a> {
        context: std::borrow::Cow<'a, str>,
        #[serde(skip_serializing_if = "Vec::is_empty")]
        attachments: Vec<std::borrow::Cow<'a, str>>,
    }

    #[derive(serde::Serialize, Debug)]
    pub struct VecLinearErrorStack<'a>(Vec<LinearErrorStack<'a>>);

    impl<'a> From<Vec<NestedErrorStack<'a>>> for VecLinearErrorStack<'a> {
        fn from(value: Vec<NestedErrorStack<'a>>) -> Self {
            let multi_layered_errors: Vec<_> = value
                .into_iter()
                .flat_map(|current_error| {
                    [LinearErrorStack {
                        context: current_error.context,
                        attachments: current_error.attachments,
                    }]
                    .into_iter()
                    .chain(Into::<VecLinearErrorStack<'a>>::into(current_error.sources).0)
                })
                .collect();
            Self(multi_layered_errors)
        }
    }
}
#[cfg(feature = "detailed_errors")]
pub use error_stack_parsing::*;

#[derive(Debug, Clone, thiserror::Error)]
pub enum RoutingError {
    #[error("Merchant routing algorithm not found in cache")]
    CacheMiss,
    #[error("Final connector selection failed")]
    ConnectorSelectionFailed,
    #[error("[DSL] Missing required field in payment data: '{field_name}'")]
    DslMissingRequiredField { field_name: String },
    #[error("The lock on the DSL cache is most probably poisoned")]
    DslCachePoisoned,
    #[error("Expected DSL to be saved in DB but did not find")]
    DslMissingInDb,
    #[error("Unable to parse DSL from JSON")]
    DslParsingError,
    #[error("Failed to initialize DSL backend")]
    DslBackendInitError,
    #[error("Error updating merchant with latest dsl cache contents")]
    DslMerchantUpdateError,
    #[error("Error executing the DSL")]
    DslExecutionError,
    #[error("Final connector selection failed")]
    DslFinalConnectorSelectionFailed,
    #[error("[DSL] Received incorrect selection algorithm as DSL output")]
    DslIncorrectSelectionAlgorithm,
    #[error("there was an error saving/retrieving values from the kgraph cache")]
    KgraphCacheFailure,
    #[error("failed to refresh the kgraph cache")]
    KgraphCacheRefreshFailed,
    #[error("there was an error during the kgraph analysis phase")]
    KgraphAnalysisError,
    #[error("'profile_id' was not provided")]
    ProfileIdMissing,
    #[error("the profile was not found in the database")]
    ProfileNotFound,
    #[error("failed to fetch the fallback config for the merchant")]
    FallbackConfigFetchFailed,
    #[error("Invalid connector name received: '{0}'")]
    InvalidConnectorName(String),
    #[error("The routing algorithm in merchant account had invalid structure")]
    InvalidRoutingAlgorithmStructure,
    #[error("Volume split failed")]
    VolumeSplitFailed,
    #[error("Unable to parse metadata")]
    MetadataParsingError,
    #[error("Unable to retrieve success based routing config")]
    SuccessBasedRoutingConfigError,
    #[error("Params not found in success based routing config")]
    SuccessBasedRoutingParamsNotFoundError,
    #[error("Unable to calculate success based routing config from dynamic routing service")]
    SuccessRateCalculationError,
    #[error("Success rate client from dynamic routing gRPC service not initialized")]
    SuccessRateClientInitializationError,
    #[error("Elimination client from dynamic routing gRPC service not initialized")]
    EliminationClientInitializationError,
    #[error("Unable to analyze elimination routing config from dynamic routing service")]
    EliminationRoutingCalculationError,
    #[error("Params not found in elimination based routing config")]
    EliminationBasedRoutingParamsNotFoundError,
    #[error("Unable to retrieve elimination based routing config")]
    EliminationRoutingConfigError,
    #[error(
        "Invalid elimination based connector label received from dynamic routing service: '{0}'"
    )]
    InvalidEliminationBasedConnectorLabel(String),
    #[error("Unable to convert from '{from}' to '{to}'")]
    GenericConversionError { from: String, to: String },
    #[error("Invalid success based connector label received from dynamic routing service: '{0}'")]
    InvalidSuccessBasedConnectorLabel(String),
    #[error("unable to find '{field}'")]
    GenericNotFoundError { field: String },
    #[error("Unable to deserialize from '{from}' to '{to}'")]
    DeserializationError { from: String, to: String },
    #[error("Unable to retrieve contract based routing config")]
    ContractBasedRoutingConfigError,
    #[error("Params not found in contract based routing config")]
    ContractBasedRoutingParamsNotFoundError,
    #[error("Unable to calculate contract score from dynamic routing service: '{err}'")]
    ContractScoreCalculationError { err: String },
    #[error("Unable to update contract score on dynamic routing service")]
    ContractScoreUpdationError,
    #[error("contract routing client from dynamic routing gRPC service not initialized")]
    ContractRoutingClientInitializationError,
    #[error("Invalid contract based connector label received from dynamic routing service: '{0}'")]
    InvalidContractBasedConnectorLabel(String),
    #[error("Failed to perform routing in open_router")]
    OpenRouterCallFailed,
    #[error("Error from open_router: {0}")]
    OpenRouterError(String),
    #[error("Decision engine responded with validation error: {0}")]
    DecisionEngineValidationError(String),
    #[error("Invalid transaction type")]
    InvalidTransactionType,
    #[error("Routing events error: {message}, status code: {status_code}")]
    RoutingEventsError { message: String, status_code: u16 },
}

#[derive(Debug, Clone, thiserror::Error)]
pub enum ConditionalConfigError {
    #[error("failed to fetch the fallback config for the merchant")]
    FallbackConfigFetchFailed,
    #[error("The lock on the DSL cache is most probably poisoned")]
    DslCachePoisoned,
    #[error("Merchant routing algorithm not found in cache")]
    CacheMiss,
    #[error("Expected DSL to be saved in DB but did not find")]
    DslMissingInDb,
    #[error("Unable to parse DSL from JSON")]
    DslParsingError,
    #[error("Failed to initialize DSL backend")]
    DslBackendInitError,
    #[error("Error executing the DSL")]
    DslExecutionError,
    #[error("Error constructing the Input")]
    InputConstructionError,
}

#[derive(Debug, thiserror::Error)]
pub enum NetworkTokenizationError {
    #[error("Failed to save network token in vault")]
    SaveNetworkTokenFailed,
    #[error("Failed to fetch network token details from vault")]
    FetchNetworkTokenFailed,
    #[error("Failed to encode network token vault request")]
    RequestEncodingFailed,
    #[error("Failed to deserialize network token service response")]
    ResponseDeserializationFailed,
    #[error("Failed to delete network token")]
    DeleteNetworkTokenFailed,
    #[error("Network token service not configured")]
    NetworkTokenizationServiceNotConfigured,
    #[error("Failed while calling Network Token Service API")]
    ApiError,
    #[error("Network Tokenization is not enabled for profile")]
    NetworkTokenizationNotEnabledForProfile,
    #[error("Network Tokenization is not supported for {message}")]
    NotSupported { message: String },
    #[error("Failed to encrypt the NetworkToken payment method details")]
    NetworkTokenDetailsEncryptionFailed,
}

#[derive(Debug, thiserror::Error)]
pub enum BulkNetworkTokenizationError {
    #[error("Failed to validate card details")]
    CardValidationFailed,
    #[error("Failed to validate payment method details")]
    PaymentMethodValidationFailed,
    #[error("Failed to assign a customer to the card")]
    CustomerAssignmentFailed,
    #[error("Failed to perform BIN lookup for the card")]
    BinLookupFailed,
    #[error("Failed to tokenize the card details with the network")]
    NetworkTokenizationFailed,
    #[error("Failed to store the card details in locker")]
    VaultSaveFailed,
    #[error("Failed to create a payment method entry")]
    PaymentMethodCreationFailed,
    #[error("Failed to update the payment method")]
    PaymentMethodUpdationFailed,
}

#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
#[derive(Debug, thiserror::Error)]
pub enum RevenueRecoveryError {
    #[error("Failed to fetch payment intent")]
    PaymentIntentFetchFailed,
    #[error("Failed to fetch payment attempt")]
    PaymentAttemptFetchFailed,
    #[error("Failed to fetch payment attempt")]
    PaymentAttemptIdNotFound,
    #[error("Failed to get revenue recovery invoice webhook")]
    InvoiceWebhookProcessingFailed,
    #[error("Failed to get revenue recovery invoice transaction")]
    TransactionWebhookProcessingFailed,
    #[error("Failed to create payment intent")]
    PaymentIntentCreateFailed,
    #[error("Source verification failed for billing connector")]
    WebhookAuthenticationFailed,
    #[error("Payment merchant connector account not found using account reference id")]
    PaymentMerchantConnectorAccountNotFound,
    #[error("Failed to fetch primitive date_time")]
    ScheduleTimeFetchFailed,
    #[error("Failed to create process tracker")]
    ProcessTrackerCreationError,
    #[error("Failed to get the response from process tracker")]
    ProcessTrackerResponseError,
    #[error("Billing connector psync call failed")]
    BillingConnectorPaymentsSyncFailed,
    #[error("Billing connector invoice sync call failed")]
    BillingConnectorInvoiceSyncFailed,
    #[error("Failed to fetch connector customer ID")]
    CustomerIdNotFound,
    #[error("Failed to get the retry count for payment intent")]
    RetryCountFetchFailed,
    #[error("Failed to get the billing threshold retry count")]
    BillingThresholdRetryCountFetchFailed,
    #[error("Failed to get the retry algorithm type")]
    RetryAlgorithmTypeNotFound,
    #[error("Failed to update the retry algorithm type")]
    RetryAlgorithmUpdationFailed,
    #[error("Failed to create the revenue recovery attempt data")]
    RevenueRecoveryAttemptDataCreateFailed,
    #[error("Failed to insert the revenue recovery payment method data in redis")]
    RevenueRecoveryRedisInsertFailed,
}


// Struct: RedisSettings
// File: crates/redis_interface/src/types.rs
// Module: redis_interface
// Implementations: 2
// Traits: Default

pub struct RedisSettings


// Function: calculate_check_sum
// File: crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
// Module: hyperswitch_connectors

pub fn calculate_check_sum(
    req: FiuuRecurringRequest,
) -> CustomResult<Secret<String>, errors::ConnectorError>


// Implementation: impl api::RefundExecute for for Itaubank
// File: crates/hyperswitch_connectors/src/connectors/itaubank.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl api::RefundExecute for for Itaubank


// Struct: GpaymentsAuthenticationSuccessResponse
// File: crates/hyperswitch_connectors/src/connectors/gpayments/gpayments_types.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct GpaymentsAuthenticationSuccessResponse


// Struct: ConnectorParamsWithFileUploadUrl
// File: crates/hyperswitch_domain_models/src/connector_endpoints.rs
// Module: hyperswitch_domain_models
// Implementations: 0

pub struct ConnectorParamsWithFileUploadUrl


// Struct: ActivePaymentsMetricRow
// File: crates/analytics/src/active_payments/metrics.rs
// Module: analytics
// Implementations: 0

pub struct ActivePaymentsMetricRow


// Struct: WorldpayAuthType
// File: crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct WorldpayAuthType


// Trait: ForeignTryFrom
// File: crates/payment_methods/src/helpers.rs
// Module: payment_methods

// Documentation: Trait for converting from one foreign type to another

pub trait ForeignTryFrom<F>: Sized


// Implementation: impl Responder
// File: crates/router/src/routes/api_keys.rs
// Module: router
// Methods: 0 total (0 public)

impl Responder


// Struct: MerchantConnectorInfo
// File: crates/api_models/src/admin.rs
// Module: api_models
// Implementations: 1

pub struct MerchantConnectorInfo


// Struct: AirwallexRefundRequest
// File: crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct AirwallexRefundRequest


// Struct: ItaubankUpdateTokenResponse
// File: crates/hyperswitch_connectors/src/connectors/itaubank/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct ItaubankUpdateTokenResponse


// File: crates/router/src/types/api/configs.rs
// Module: router
// Public structs: 2

#[derive(Clone, serde::Serialize, Debug, serde::Deserialize)]
pub struct Config {
    pub key: String,
    pub value: String,
}

#[derive(Clone, serde::Deserialize, Debug, serde::Serialize)]
pub struct ConfigUpdate {
    #[serde(skip_deserializing)]
    pub key: String,
    pub value: String,
}


// Implementation: impl api::PaymentCapture for for Coingate
// File: crates/hyperswitch_connectors/src/connectors/coingate.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl api::PaymentCapture for for Coingate