    ///
    /// This field is limited to a maximum of 16 characters.
    ///
    /// This field is required unless shipping information is the same as billing information, or market or regional
    /// mandate restricts sending this information.
    ship_addr_post_code: Option<masking::Secret<String>>,

    /// The state or province of the shipping address associated with the card used for this purchase.
    ///
    /// This field is limited to 3 characters. The value should be the country subdivision code defined in ISO 3166-2.
    ///
    /// This field is required unless shipping information is the same as billing information, or State is not applicable
    /// for this country, or market or regional mandate restricts sending this information.
    ship_addr_state: Option<masking::Secret<String>>,

    /// Tax ID is the Cardholder's tax identification.
    ///
    /// The value is limited to 45 characters.
    ///
    /// This field is required depending on the rules provided by the Directory Server.
    /// Available for supporting EMV 3DS 2.3.1 and later versions.
    tax_id: Option<String>,
}

impl
    TryFrom<(
        hyperswitch_domain_models::address::Address,
        Option<hyperswitch_domain_models::address::Address>,
    )> for Cardholder
{
    type Error = error_stack::Report<ConnectorError>;
    fn try_from(
        (billing_address, shipping_address): (
            hyperswitch_domain_models::address::Address,
            Option<hyperswitch_domain_models::address::Address>,
        ),
    ) -> Result<Self, Self::Error> {
        Ok(Self {
            addr_match: None,
            bill_addr_city: billing_address
                .address
                .as_ref()
                .and_then(|add| add.city.clone()),
            bill_addr_country: billing_address.address.as_ref().and_then(|add| {
                add.country.map(|country| {
                    common_enums::Country::from_alpha2(country)
                        .to_numeric()
                        .to_string()
                })
            }),
            bill_addr_line1: billing_address
                .address
                .as_ref()
                .and_then(|add| add.line1.clone()),
            bill_addr_line2: billing_address
                .address
                .as_ref()
                .and_then(|add| add.line2.clone()),
            bill_addr_line3: billing_address
                .address
                .as_ref()
                .and_then(|add| add.line3.clone()),
            bill_addr_post_code: billing_address
                .address
                .as_ref()
                .and_then(|add| add.zip.clone()),
            bill_addr_state: billing_address
                .address
                .as_ref()
                .and_then(|add| add.to_state_code_as_optional().transpose())
                .transpose()?,
            email: billing_address.email,
            home_phone: billing_address
                .phone
                .clone()
                .map(PhoneNumber::try_from)
                .transpose()?,
            mobile_phone: billing_address
                .phone
                .clone()
                .map(PhoneNumber::try_from)
                .transpose()?,
            work_phone: billing_address
                .phone
                .clone()
                .map(PhoneNumber::try_from)
                .transpose()?,
            cardholder_name: billing_address.address.and_then(|address| {
                address
                    .get_optional_full_name()
                    .map(|name| masking::Secret::new(unidecode(&name.expose())))
            }),
            ship_addr_city: shipping_address
                .as_ref()
                .and_then(|shipping_add| shipping_add.address.as_ref())
                .and_then(|add| add.city.clone()),
            ship_addr_country: shipping_address
                .as_ref()
                .and_then(|shipping_add| shipping_add.address.as_ref())
                .and_then(|add| {
                    add.country.map(|country| {
                        common_enums::Country::from_alpha2(country)
                            .to_numeric()
                            .to_string()
                    })
                }),
            ship_addr_line1: shipping_address
                .as_ref()
                .and_then(|shipping_add| shipping_add.address.as_ref())
                .and_then(|add| add.line1.clone()),
            ship_addr_line2: shipping_address
                .as_ref()
                .and_then(|shipping_add| shipping_add.address.as_ref())
                .and_then(|add| add.line2.clone()),
            ship_addr_line3: shipping_address
                .as_ref()
                .and_then(|shipping_add| shipping_add.address.as_ref())
                .and_then(|add| add.line3.clone()),
            ship_addr_post_code: shipping_address
                .as_ref()
                .and_then(|shipping_add| shipping_add.address.as_ref())
                .and_then(|add| add.zip.clone()),
            ship_addr_state: shipping_address
                .as_ref()
                .and_then(|shipping_add| shipping_add.address.as_ref())
                .and_then(|add| add.to_state_code_as_optional().transpose())
                .transpose()?,
            tax_id: None,
        })
    }
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct PhoneNumber {
    /// Country Code of the phone, limited to 1-3 characters
    #[serde(rename = "cc")]
    country_code: Option<String>,
    subscriber: Option<masking::Secret<String>>,
}

impl TryFrom<hyperswitch_domain_models::address::PhoneDetails> for PhoneNumber {
    type Error = error_stack::Report<ConnectorError>;
    fn try_from(
        value: hyperswitch_domain_models::address::PhoneDetails,
    ) -> Result<Self, Self::Error> {
        Ok(Self {
            country_code: Some(value.extract_country_code()?),
            subscriber: value.number,
        })
    }
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Purchase {
    /// Indicates the maximum number of authorisations permitted for instalment payments.
    ///
    /// The field is limited to a maximum of 3 characters and value shall be greater than 1.
    ///
    /// The field is required if the Merchant and Cardholder have agreed to installment payments, i.e. if 3DS Requestor
    /// Authentication Indicator = 03. Omitted if not an installment payment authentication.
    ///
    /// Starting from EMV 3DS 2.3.1:
    /// Additionally this field is required for deviceChannel = 03 (3RI) if threeRIInd = 02.
    pub purchase_instal_data: Option<i32>,

    /// Merchant's assessment of the level of fraud risk for the specific authentication for both the cardholder and the
    /// authentication being conducted.
    ///
    /// The field is optional but strongly recommended to include.
    pub merchant_risk_indicator: Option<MerchantRiskIndicator>,

    /// Purchase amount in minor units of currency with all punctuation removed. When used in conjunction with the Purchase
    /// Currentcy Exponent field, proper punctuation can be calculated. Example: If the purchase amount is USD 123.45,
    /// element will contain the value 12345. The field is limited to maximum 48 characters.
    ///
    /// This field is required for 02 - NPA message category if 3DS Requestor Authentication Indicator = 02 or 03.
    ///
    /// Starting from EMV 3DS 2.3.1:
    /// Additionally this field is required for messageCategory = 02 (NPA) if threeRIInd = 01, 02, 06, 07, 08, 09, or 11.
    pub purchase_amount: Option<i64>,

    /// Currency in which purchase amount is expressed. The value is limited to 3 numeric characters and is represented by
    /// the ISO 4217 three-digit currency code, except 955-964 and 999.
    ///
    /// This field is required for requests where messageCategory = 01-PA and for 02-NPA if 3DS Requestor Authentication
    /// Indicator = 02 or 03.
    ///
    /// Starting from EMV 3DS 2.3.1:
    /// Additionally this field is required for messageCategory = 02 (NPA) if threeRIInd = 01, 02, 06, 07, 08, 09, or 11.
    pub purchase_currency: String,

    /// Minor units of currency as specified in the ISO 4217 currency exponent. The field is limited to 1 character and it
    /// is required for 01-PA and for 02-NPA if 3DS Requestor Authentication Indicator = 02 or 03.
    ///
    /// Example: for currency USD the exponent should be 2, and for Yen the exponent should be 0.
    ///
    /// Starting from EMV 3DS 2.3.1:
    /// Additionally this field is required for messageCategory = 02 (NPA) if threeRIInd = 01, 02, 06, 07, 08, 09, or 11.
    pub purchase_exponent: u8,

    /// Date and time of the purchase, converted into UTC. The field is limited to 14 characters,
    /// formatted as YYYYMMDDHHMMSS.
    ///
    /// This field is required for 01-PA and for 02-NPA, if 3DS Requestor Authentication Indicator = 02 or 03.
    ///
    /// Starting from EMV 3DS 2.3.1:
    /// Additionally this field is required for messageCategory = 02 (NPA) if threeRIInd = 01, 02, 06, 07, 08, 09, or 11.
    pub purchase_date: Option<String>,

    /// Date after which no further authorizations shall be performed. This field is limited to 8 characters, and the
    /// accepted format is YYYYMMDD.
    ///
    /// This field is required for 01-PA and for 02-NPA, if 3DS Requestor Authentication Indicator = 02 or 03.
    ///
    /// Starting from EMV 3DS 2.3.1:
    /// This field is required if recurringInd = 01.
    pub recurring_expiry: Option<String>,

    /// Indicates the minimum number of days between authorizations. The field is limited to maximum 4 characters.
    ///
    /// This field is required if 3DS Requestor Authentication Indicator = 02 or 03.
    ///
    /// Starting from EMV 3DS 2.3.1:
    /// This field is required if recurringInd = 01
    pub recurring_frequency: Option<i32>,

    /// Identifies the type of transaction being authenticated. The values are derived from ISO 8583. Accepted values are:
    ///    - 01 -> Goods / Service purchase
    ///    - 03 -> Check Acceptance
    ///    - 10 -> Account Funding
    ///    - 11 -> Quasi-Cash Transaction
    ///    - 28 -> Prepaid activation and Loan
    ///
    /// This field is required in some markets. Otherwise, the field is optional.
    ///
    /// This field is required if 3DS Requestor Authentication Indicator = 02 or 03.
    pub trans_type: Option<String>,

    /// Recurring amount after first/promotional payment in minor units of currency with all punctuation removed.
    /// Example: If the recurring amount is USD 123.45, element will contain the value 12345. The field is limited to
    /// maximum 48 characters.
    ///
    /// The field is required if threeDSRequestorAuthenticationInd = 02 or 03 OR threeRIInd = 01 or 02 AND
    /// purchaseAmount != recurringAmount AND recurringInd = 01.
    ///
    /// Available for supporting EMV 3DS 2.3.1 and later versions.
    pub recurring_amount: Option<i64>,

    /// Currency in which recurring amount is expressed. The value is limited to 3 numeric characters and is represented by
    /// the ISO 4217 three-digit currency code, except 955-964 and 999.
    ///
    /// This field is required if recurringAmount is present.
    ///
    /// Available for supporting EMV 3DS 2.3.1 and later versions.
    pub recurring_currency: Option<String>,

    /// Minor units of currency as specified in the ISO 4217 currency exponent. Example: USD = 2, Yen = 0. The value is
    /// limited to 1 numeric character.
    ///
    /// This field is required if recurringAmount is present.
    ///
    /// Available for supporting EMV 3DS 2.3.1 and later versions.
    pub recurring_exponent: Option<i32>,

    /// Effective date of new authorised amount following first/promotional payment in recurring transaction. The value
    /// is limited to 8 characters. Accepted format: YYYYMMDD.
    ///
    /// This field is required if recurringInd = 01.
    ///
    /// Available for supporting EMV 3DS 2.3.1 and later versions.
    pub recurring_date: Option<String>,

    /// Part of the indication whether the recurring or instalment payment has a fixed or variable amount.
    ///
    /// Accepted values are:
    ///    - 01 -> Fixed Purchase Amount
    ///    - 02 -> Variable Purchase Amount
    ///    - 03–79 -> Reserved for EMVCo future use (values invalid until defined by EMVCo)
    ///    - 80-99 -> PS-specific value (dependent on the payment scheme type)
    ///
    /// Available for supporting EMV 3DS 2.3.1 and later versions.
    pub amount_ind: Option<String>,

    /// Part of the indication whether the recurring or instalment payment has a fixed or variable frequency.
    ///
    /// Accepted values are:
    ///    - 01 -> Fixed Frequency
    ///    - 02 -> Variable Frequency
    ///    - 03–79 -> Reserved for EMVCo future use (values invalid until defined by EMVCo)
    ///    - 80-99 -> PS-specific value (dependent on the payment scheme type)
    ///
    /// Available for supporting EMV 3DS 2.3.1 and later versions.
    pub frequency_ind: Option<String>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct MerchantRiskIndicator {
    /// Indicates the shipping method chosen for the transaction.
    ///
    /// Merchants must choose the Shipping Indicator code that most accurately describes the cardholder's specific transaction.
    /// If one or more items are included in the sale, use the Shipping Indicator code for the physical goods, or if all digital goods,
    /// use the code that describes the most expensive item.
    ///
    /// Accepted values:
    ///   - Ship to cardholder's billing address (01)
    ///   - Ship to another verified address on file with merchant (02)
    ///   - Ship to address that is different than the cardholder's billing address (03)
    ///   - Ship to Store / Pick-up at local store (Store address shall be populated in shipping address fields) (04)
    ///   - Digital goods (includes online services, electronic gift cards and redemption codes) (05)
    ///   - Travel and Event tickets, not shipped (06)
    ///   - Other (for example, Gaming, digital services not shipped, e-media subscriptions, etc.) (07)
    ///   - PS-specific value (dependent on the payment scheme type) (80-81)
    ///
    /// Starting from EMV 3DS 2.3.1:
    /// Changed values to shipIndicator -> Accepted values are:
    ///                        - 01 -> Ship to cardholder's billing address
    ///                        - 02 -> Ship to another verified address on file with merchant
    ///                        - 03 -> Ship to address that is different than the cardholder's billing address
    ///                        - 04 -> "Ship to Store" / Pick-up at local store (Store address shall be populated in shipping
    ///                              address fields)
    ///                        - 05 -> Digital goods (includes online services, electronic gift cards and redemption codes)
    ///                        - 06 -> Travel and Event tickets, not shipped
    ///                        - 07 -> Other (for example, Gaming, digital services not shipped, e-media subscriptions, etc.)
    ///                        - 08 -> Pick-up and go delivery
    ///                        - 09 -> Locker delivery (or other automated pick-up)
    ship_indicator: Option<String>,

    /// Indicates the merchandise delivery timeframe.
    ///
    /// Accepted values:
    ///   - Electronic Delivery (01)
    ///   - Same day shipping (02)
    ///   - Overnight shipping (03)
    ///   - Two-day or more shipping (04)
    delivery_timeframe: Option<String>,

    /// For electronic delivery, the email address to which the merchandise was delivered.
    delivery_email_address: Option<String>,

    /// Indicates whether the cardholder is reordering previously purchased merchandise.
    ///
    /// Accepted values:
    ///   - First time ordered (01)
    ///   - Reordered (02)
    reorder_items_ind: Option<String>,

    /// Indicates whether Cardholder is placing an order for merchandise with a future availability or release date.
    ///
    /// Accepted values:
    ///   - Merchandise available (01)
    ///   - Future availability (02)
    pre_order_purchase_ind: Option<String>,

    /// For a pre-ordered purchase, the expected date that the merchandise will be available.
    ///
    /// Date format: YYYYMMDD
    pre_order_date: Option<String>,

    /// For prepaid or gift card purchase, the purchase amount total of prepaid or gift card(s) in major units.
    gift_card_amount: Option<i32>,

    /// For prepaid or gift card purchase, the currency code of the card as defined in ISO 4217 except 955 - 964 and 999.
    gift_card_curr: Option<String>, // ISO 4217 currency code

    /// For prepaid or gift card purchase, total count of individual prepaid or gift cards/codes purchased.
    ///
    /// Field is limited to 2 characters.
    gift_card_count: Option<i32>,
    /// Starting from EMV 3DS 2.3.1.1:
    /// New field introduced:
    /// - transChar -> Indicates to the ACS specific transactions identified by the Merchant.
    ///      - Size: Variable, 1-2 elements. JSON Data Type: Array of String. Accepted values:
    ///          - 01 -> Cryptocurrency transaction
    ///          - 02 -> NFT transaction
    trans_char: Option<String>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct AcquirerData {
    /// Acquiring institution identification code as assigned by the DS receiving the AReq message.
    ///
    /// This field is limited to 11 characters. This field can be omitted if it there is a MerchantAcquirer already configured for 3DS Server,
    /// referenced by the acquirerMerchantId.
    ///
    /// This field is required if no MerchantAcquirer is present for the acquirer BIN in the 3DS Server configuration and
    /// for requests where messageCategory = 01 (PA). For requests where messageCategory=02 (NPA), the field is required
    /// only if scheme is Mastercard, for other schemes it is optional.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub acquirer_bin: Option<String>,

    /// Acquirer-assigned Merchant identifier.
    ///
    /// This may be the same value that is used in authorization requests sent on behalf of the 3DS Requestor and is represented in ISO 8583 formatting requirements.
    /// The field is limited to maximum 35 characters. Individual Directory Servers may impose specific format and character requirements on
    /// the contents of this field.
    ///
    /// This field will be used to identify the Directory Server where the AReq will be sent and the acquirerBin from the 3DS Server configuration.
    /// If no MerchantAcquirer configuration is present in the 3DS Server, the DirectoryServer information will be resolved from the scheme to which the cardholder account belongs to.
    ///
    /// This field is required if merchantConfigurationId is not provided in the request and messageCategory = 01 (PA).
    /// For Mastercard, if merchantConfigurationId is not provided, the field must be present if messageCategory = 02 (NPA).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub acquirer_merchant_id: Option<String>,

    /// Acquirer Country Code.
    ///
    /// This is the code of the country where the acquiring institution is located. The specified
    /// length of this field is 3 characters and will accept values according to the ISO 3166-1 numeric three-digit
    /// country code.
    ///
    /// The Directory Server may edit the value of this field provided by the 3DS Server.
    ///
    /// This field is required.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub acquirer_country_code: Option<String>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
#[serde_with::skip_serializing_none]
pub struct MerchantData {
    /// ID of the merchant. This value will be used to find merchant information from the configuration.
    /// From the merchant configuration the 3DS Server can fill the other values (mcc, merchantCountryCode and merchantName), if provided.
    ///
    /// This field can be left out if merchant information are provided in the request.
    pub merchant_configuration_id: Option<String>,

    /// Merchant Category Code. This is the DS-specific code describing the Merchant's type of business, product or service.
    /// The field is limited to 4 characters. The value correlates to the Merchant Category Code as defined by each Payment System or DS.
    ///
    /// If not present in the request it will be filled from the merchant configuration referenced by the merchantConfigurationId.
    ///
    /// This field is required for messageCategory=01 (PA) and optional, but strongly recommended for 02 (NPA).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mcc: Option<String>,

    /// Country code for the merchant. This value correlates to the Merchant Country Code as defined by each Payment System or DS.
    /// The field is limited to 3 characters accepting ISO 3166-1 format, except 901-999.
    ///
    /// If not present in the request it will be filled from the merchant configuration referenced by the merchantConfigurationId.
    ///
    /// This field is required for messageCategory=01 (PA) and optional, but strongly recommended for 02 (NPA).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub merchant_country_code: Option<String>,

    /// Merchant name assigned by the Acquirer or Payment System. This field is limited to maximum 40 characters,
    /// and it is the same name used in the authorisation message as defined in ISO 8583.
    ///
    /// If not present in the request it will be filled from the merchant configuration referenced by the merchantConfigurationId.
    ///
    /// This field is required for messageCategory=01 (PA) and optional, but strongly recommended for 02 (NPA).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub merchant_name: Option<String>,

    /// Fully qualified URL of the merchant that receives the CRes message or Error Message.
    /// Incorrect formatting will result in a failure to deliver the notification of the final CRes message.
    /// This field is limited to 256 characters.
    ///
    /// This field should be present if the merchant will receive the final CRes message and the device channel is BROWSER.
    /// If not present in the request it will be filled from the notificationURL configured in the XML or database configuration.
    #[serde(rename = "notificationURL")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub notification_url: Option<String>,

    /// Each DS provides rules for the 3DS Requestor ID. The 3DS Requestor is responsible for providing the 3DS Requestor ID according to the DS rules.
    ///
    /// This value is mandatory, therefore it should be either configured for each Merchant Acquirer, or should be
    /// passed in the transaction payload as part of the Merchant data.
    #[serde(rename = "threeDSRequestorId")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub three_ds_requestor_id: Option<String>,

    /// Each DS provides rules for the 3DS Requestor Name. The 3DS Requestor is responsible for providing the 3DS Requestor Name according to the DS rules.
    ///
    /// This value is mandatory, therefore it should be either configured for each Merchant Acquirer, or should be
    /// passed in the transaction payload as part of the Merchant data.
    #[serde(rename = "threeDSRequestorName")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub three_ds_requestor_name: Option<String>,

    /// Set whitelisting status of the merchant.
    ///
    /// The field is optional and if value is not present, the whitelist remains unchanged.
    /// This field is only available for supporting EMV 3DS 2.2.0.
    pub white_list_status: Option<WhitelistStatus>,

    /// Set trustlisting status of the merchant.
    ///
    /// The field is optional and if value is not present, the trustlist remains unchanged.
    /// From EMV 3DS 2.3.1 this field replaces whiteListStatus.
    pub trust_list_status: Option<WhitelistStatus>,

    /// Additional transaction information for transactions where merchants submit transaction details on behalf of another entity.
    /// The accepted value length is 1-50 elements.
    ///
    /// This field is optional.
    pub seller_info: Option<Vec<SellerInfo>>,

    /// Fully qualified URL of the merchant that receives the RRes message or Error Message.
    /// Incorrect formatting will result in a failure to deliver the notification of the final RRes message.
    /// This field is limited to 256 characters.
    ///
    /// This field is not mandatory and could be present if the Results Response (in case of a challenge transaction)
    /// should be sent to a dynamic URL different from the one present in the configuration, only if dynamic provision
    /// of the Results Response notification URL is allowed per the license.
    ///
    /// If not present in the request it will be filled from the notificationURL configured in the XML or database
    /// configuration.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub results_response_notification_url: Option<String>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub enum WhitelistStatus {
    /// 3DS Requestor is whitelisted by cardholder
    Y,
    /// 3DS Requestor is not whitelisted by cardholder
    N,
    /// Not eligible as determined by issuer
    E,
    /// Pending confirmation by cardholder
    P,
    /// Cardholder rejected
    R,
    /// Whitelist status unknown, unavailable, or does not apply.
    U,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
#[serde_with::skip_serializing_none]
pub struct SellerInfo {
    /// Name of the Seller. The value length is maximum 100 characters. This field is required.
    seller_name: String,

    /// Merchant-assigned Seller identifier. If this data element is present, this must match the Seller ID field
    /// in the Seller Information object. The value length is maximum 50 characters. This field is required if
    /// sellerId in multiTransaction object is present.
    seller_id: Option<String>,

    /// Business name of the Seller. The value length is maximum 100 characters. This field is optional.
    seller_business_name: Option<String>,

    /// Date converted into UTC that the Seller started using the Merchant's services. The accepted value length is
    /// 8 characters. The accepted format is: YYYYMMDD.
    seller_acc_date: Option<String>,

    /// First line of the business or contact street address of the Seller. The value length is maximum 50 characters.
    /// This field is optional.
    seller_addr_line1: Option<String>,

    /// Second line of the business or contact street address of the Seller. The value length is maximum 50 characters.
    /// This field is optional.
    seller_addr_line2: Option<String>,

    /// Third line of the business or contact street address of the Seller. The value length is maximum 50 characters.
    /// This field is optional.
    seller_addr_line3: Option<String>,

    /// Business or contact city of the Seller. The value length is maximum 50 characters. This field is optional.
    seller_addr_city: Option<String>,

    /// Business or contact state or province of the Seller. The value length is maximum 3 characters. Accepted values
    /// are: Country subdivision code defined in ISO 3166-2. For example, using the ISO entry US-CA (California,
    /// United States), the correct value for this field = CA. Note that the country and hyphen are not included in
    /// this value. This field is optional.
    seller_addr_state: Option<String>,

    /// Business or contact ZIP or other postal code of the Seller. The value length is maximum 16 characters.
    /// This field is optional.
    seller_addr_post_code: Option<String>,

    /// Business or contact country of the Seller. The accepted value length is 3 characters. Accepted values are
    /// ISO 3166-1 numeric three-digit country code, except 955-964 and 999. This field is optional.
    seller_addr_country: Option<String>,

    /// Business or contact email address of the Seller. The value length is maximum 254 characters. Accepted values
    /// shall meet requirements of Section 3.4 of IETF RFC 5322. This field is optional.
    seller_email: Option<String>,

    /// Business or contact phone number of the Seller. Country Code and Subscriber sections of the number represented
    /// by the following named fields:
    ///     - cc -> Accepted value length is 1-3 characters.
    ///     - subscriber -> Accepted value length is maximum 15 characters.
    /// This field is optional.
    seller_phone: Option<PhoneNumber>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Browser {
    /// Exact content of the HTTP accept headers as sent to the 3DS Requestor from the Cardholder's browser.
    /// This field is limited to maximum 2048 characters  and if the total length exceeds the limit, the 3DS Server
    /// truncates the excess portion.
    ///
    /// This field is required for requests where deviceChannel=02 (BRW).
    browser_accept_header: Option<String>,

    /// IP address of the browser as returned by the HTTP headers to the 3DS Requestor. The field is limited to maximum 45
    /// characters and the accepted values are as following:
    ///      - IPv4 address is represented in the dotted decimal format of 4 sets of decimal numbers separated by dots. The
    ///        decimal number in each and every set is in the range 0 - 255. Example: 1.12.123.255
    ///      - IPv6 address is represented as eight groups of four hexadecimal digits, each group representing 16 bits (two
    ///        octets). The groups are separated by colons (:). Example: 2011:0db8:85a3:0101:0101:8a2e:0370:7334
    ///
    /// This field is required for requests when deviceChannel = 02 (BRW) where regionally acceptable.
    #[serde(rename = "browserIP")]
    browser_ip: Option<masking::Secret<String, common_utils::pii::IpAddress>>,

    /// Boolean that represents the ability of the cardholder browser to execute Java. Value is returned from the
    /// navigator.javaEnabled property.
    ///
    /// Depending on the message version, the field is required for requests:
    /// - with message version = 2.1.0 and deviceChannel = 02 (BRW).
    /// - with message version = 2.2.0 and deviceChannel = 02 (BRW) and browserJavascriptEnabled = true.
    browser_java_enabled: Option<bool>,

    /// Value representing the browser language as defined in IETF BCP47.
    ///
    /// Until EMV 3DS 2.2.0:
    /// The value is limited to 1-8 characters. If the value exceeds 8 characters, it will be truncated to a
    /// semantically valid value, if possible. The value is returned from navigator.language property.
    ///
    /// This field is required for requests where deviceChannel = 02 (BRW)
    /// In other cases this field is optional.
    ///
    /// Starting from EMV 3DS 2.3.1:
    /// The value is limited to 35 characters. If the value exceeds 35 characters, it will be truncated to a
    /// semantically valid value, if possible. The value is returned from navigator.language property.
    ///
    /// This field is required for requests where deviceChannel = 02 (BRW) and browserJavascriptEnabled = true.
    /// In other cases this field is optional.
    browser_language: Option<String>,

    /// Value representing the bit depth of the colour palette for displaying images, in bits per pixel. Obtained from
    /// Cardholder browser using the screen.colorDepth property. The field is limited to 1-2 characters.
    ///
    /// Accepted values are:
    ///  - 1 -> 1 bit
    ///  - 4 -> 4 bits
    ///  - 8 -> 8 bits
    ///  - 15 -> 15 bits
    ///  - 16 -> 16 bits
    ///  - 24 -> 24 bits
    ///  - 32 -> 32 bits
    ///  - 48 -> 48 bits
    ///
    ///  If the value is not in the accepted values, it will be resolved to the first accepted value lower from the one
    ///  provided.
    ///
    /// Depending on the message version, the field is required for requests:
    /// - with message version = 2.1.0 and deviceChannel = 02 (BRW).
    /// - with message version = 2.2.0 and deviceChannel = 02 (BRW) and browserJavascriptEnabled = true.
    browser_color_depth: Option<String>,

    /// Total height of the Cardholder's screen in pixels. Value is returned from the screen.height property. The value is
    /// limited to 1-6 characters.
    ///
    /// Depending on the message version, the field is required for requests:
    /// - with message version = 2.1.0 and deviceChannel = 02 (BRW).
    /// - with message version = 2.2.0 and deviceChannel = 02 (BRW) and browserJavascriptEnabled = true.
    browser_screen_height: Option<u32>,

    /// Total width of the Cardholder's screen in pixels. Value is returned from the screen.width property. The value is
    /// limited to 1-6 characters.
    ///
    /// Depending on the message version, the field is required for requests:
    /// - with message version = 2.1.0 and deviceChannel = 02 (BRW).
    /// - with message version = 2.2.0 and deviceChannel = 02 (BRW) and browserJavascriptEnabled = true.
    browser_screen_width: Option<u32>,

    /// Time difference between UTC time and the Cardholder browser local time, in minutes. The field is limited to 1-5
    /// characters where the vauyes is returned from the getTimezoneOffset() method.
    ///
    /// Depending on the message version, the field is required for requests:
    /// - with message version = 2.1.0 and deviceChannel = 02 (BRW).
    /// - with message version = 2.2.0 and deviceChannel = 02 (BRW) and browserJavascriptEnabled = true.
    #[serde(rename = "browserTZ")]
    browser_tz: Option<i32>,

    /// Exact content of the HTTP user-agent header. The field is limited to maximum 2048 characters. If the total length of
    /// the User-Agent sent by the browser exceeds 2048 characters, the 3DS Server truncates the excess portion.
    ///
    /// This field is required for requests where deviceChannel = 02 (BRW).
    browser_user_agent: Option<String>,

    /// Dimensions of the challenge window that has been displayed to the Cardholder. The ACS shall reply with content


// Function: generic_update_with_unique_predicate_get_result
// File: crates/diesel_models/src/query/generics.rs
// Module: diesel_models

pub fn generic_update_with_unique_predicate_get_result<T, V, P, R>(
    conn: &PgPooledConn,
    predicate: P,
    values: V,
) -> StorageResult<R>
where
    T: FilterDsl<P> + HasTable<Table = T> + Table + 'static,
    V: AsChangeset<Target = <Filter<T, P> as HasTable>::Table> + Debug + 'static,
    Filter<T, P>: IntoUpdateTarget + 'static,
    UpdateStatement<
        <Filter<T, P> as HasTable>::Table,
        <Filter<T, P> as IntoUpdateTarget>::WhereClause,
        <V as AsChangeset>::Changeset,
    >: AsQuery + LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send,
    R: Send + 'static,

    // For cloning query (UpdateStatement)
    <Filter<T, P> as HasTable>::Table: Clone,
    <Filter<T, P> as IntoUpdateTarget>::WhereClause: Clone,
    <V as AsChangeset>::Changeset: Clone,
    <<Filter<T, P> as HasTable>::Table as QuerySource>::FromClause: Clone,


// Function: create_tenant_user
// File: crates/router/src/core/user.rs
// Module: router

pub fn create_tenant_user(
    state: SessionState,
    request: user_api::CreateTenantUserRequest,
) -> UserResponse<()>


// Struct: SdkEventFilter
// File: crates/analytics/src/sdk_events/filters.rs
// Module: analytics
// Implementations: 0

pub struct SdkEventFilter


// Implementation: impl RoutingAlgorithmInterface for for KafkaStore
// File: crates/router/src/db/kafka_store.rs
// Module: router
// Methods: 7 total (0 public)

impl RoutingAlgorithmInterface for for KafkaStore


// Function: delete_by_merchant_id
// File: crates/diesel_models/src/query/merchant_account.rs
// Module: diesel_models

pub fn delete_by_merchant_id(
        conn: &PgPooledConn,
        identifier: &common_utils::id_type::MerchantId,
    ) -> StorageResult<bool>


// Implementation: impl behaviour::Conversion for for Customer
// File: crates/hyperswitch_domain_models/src/customer.rs
// Module: hyperswitch_domain_models
// Methods: 3 total (0 public)

impl behaviour::Conversion for for Customer


// Struct: FrmFlowData
// File: crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs
// Module: hyperswitch_domain_models
// Implementations: 0

pub struct FrmFlowData


// File: crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs
// Module: analytics

use std::collections::HashSet;

use api_models::analytics::{
    payment_intents::{
        PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetricsBucketIdentifier,
    },
    Granularity, TimeRange,
};
use common_utils::errors::ReportSwitchExt;
use diesel_models::enums as storage_enums;
use error_stack::ResultExt;
use time::PrimitiveDateTime;

use super::PaymentIntentMetricRow;
use crate::{
    enums::AuthInfo,
    query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
    types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
};

#[derive(Default)]
pub(crate) struct PaymentProcessedAmount;

#[async_trait::async_trait]
impl<T> super::PaymentIntentMetric<T> for PaymentProcessedAmount
where
    T: AnalyticsDataSource + super::PaymentIntentMetricAnalytics,
    PrimitiveDateTime: ToSql<T>,
    AnalyticsCollection: ToSql<T>,
    Granularity: GroupByClause<T>,
    Aggregate<&'static str>: ToSql<T>,
    Window<&'static str>: ToSql<T>,
{
    async fn load_metrics(
        &self,
        dimensions: &[PaymentIntentDimensions],
        auth: &AuthInfo,
        filters: &PaymentIntentFilters,
        granularity: Option<Granularity>,
        time_range: &TimeRange,
        pool: &T,
    ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>>
    {
        let mut query_builder: QueryBuilder<T> =
            QueryBuilder::new(AnalyticsCollection::PaymentIntentSessionized);

        let mut dimensions = dimensions.to_vec();

        dimensions.push(PaymentIntentDimensions::PaymentIntentStatus);

        for dim in dimensions.iter() {
            query_builder.add_select_column(dim).switch()?;
        }
        query_builder
            .add_select_column(Aggregate::Count {
                field: None,
                alias: Some("count"),
            })
            .switch()?;

        query_builder
            .add_select_column("(attempt_count = 1) as first_attempt")
            .switch()?;
        query_builder.add_select_column("currency").switch()?;
        query_builder
            .add_select_column(Aggregate::Sum {
                field: "amount",
                alias: Some("total"),
            })
            .switch()?;
        query_builder
            .add_select_column(Aggregate::Min {
                field: "created_at",
                alias: Some("start_bucket"),
            })
            .switch()?;
        query_builder
            .add_select_column(Aggregate::Max {
                field: "created_at",
                alias: Some("end_bucket"),
            })
            .switch()?;

        filters.set_filter_clause(&mut query_builder).switch()?;

        auth.set_filter_clause(&mut query_builder).switch()?;

        time_range
            .set_filter_clause(&mut query_builder)
            .attach_printable("Error filtering time range")
            .switch()?;

        for dim in dimensions.iter() {
            query_builder
                .add_group_by_clause(dim)
                .attach_printable("Error grouping by dimensions")
                .switch()?;
        }

        query_builder
            .add_group_by_clause("first_attempt")
            .attach_printable("Error grouping by first_attempt")
            .switch()?;
        query_builder
            .add_group_by_clause("currency")
            .attach_printable("Error grouping by currency")
            .switch()?;
        if let Some(granularity) = granularity {
            granularity
                .set_group_by_clause(&mut query_builder)
                .attach_printable("Error adding granularity")
                .switch()?;
        }

        query_builder
            .add_filter_clause(
                PaymentIntentDimensions::PaymentIntentStatus,
                storage_enums::IntentStatus::Succeeded,
            )
            .switch()?;

        query_builder
            .execute_query::<PaymentIntentMetricRow, _>(pool)
            .await
            .change_context(MetricsError::QueryBuildingError)?
            .change_context(MetricsError::QueryExecutionFailure)?
            .into_iter()
            .map(|i| {
                Ok((
                    PaymentIntentMetricsBucketIdentifier::new(
                        None,
                        i.currency.as_ref().map(|i| i.0),
                        i.profile_id.clone(),
                        i.connector.clone(),
                        i.authentication_type.as_ref().map(|i| i.0),
                        i.payment_method.clone(),
                        i.payment_method_type.clone(),
                        i.card_network.clone(),
                        i.merchant_id.clone(),
                        i.card_last_4.clone(),
                        i.card_issuer.clone(),
                        i.error_reason.clone(),
                        TimeRange {
                            start_time: match (granularity, i.start_bucket) {
                                (Some(g), Some(st)) => g.clip_to_start(st)?,
                                _ => time_range.start_time,
                            },
                            end_time: granularity.as_ref().map_or_else(
                                || Ok(time_range.end_time),
                                |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
                            )?,
                        },
                    ),
                    i,
                ))
            })
            .collect::<error_stack::Result<
                HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>,
                crate::query::PostProcessingError,
            >>()
            .change_context(MetricsError::PostProcessingFailure)
    }
}


// Function: get_payment_intents_filters
// File: crates/router/src/analytics.rs
// Module: router

pub fn get_payment_intents_filters(
        state: web::Data<AppState>,
        req: actix_web::HttpRequest,
        json_payload: web::Json<GetPaymentIntentFiltersRequest>,
    ) -> impl Responder


// Implementation: impl api::PaymentVoid for for Moneris
// File: crates/hyperswitch_connectors/src/connectors/moneris.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl api::PaymentVoid for for Moneris


// Function: construct_fulfillment_router_data
// File: crates/router/src/core/fraud_check/flows/fulfillment_flow.rs
// Module: router

pub fn construct_fulfillment_router_data<'a>(
    state: &'a SessionState,
    payment_intent: &'a storage::PaymentIntent,
    payment_attempt: &storage::PaymentAttempt,
    merchant_context: &domain::MerchantContext,
    connector: String,
    fulfillment_request: FrmFulfillmentRequest,
) -> RouterResult<FrmFulfillmentRouterData>


// Struct: ElavonErrorResponse
// File: crates/hyperswitch_connectors/src/connectors/elavon/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct ElavonErrorResponse


// Implementation: impl api::revenue_recovery::RevenueRecoveryRecordBack for for Chargebee
// File: crates/hyperswitch_connectors/src/connectors/chargebee.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl api::revenue_recovery::RevenueRecoveryRecordBack for for Chargebee


// Function: refunds_list
// File: crates/openapi/src/routes/refunds.rs
// Module: openapi

pub fn refunds_list()


// File: crates/euclid_wasm/src/types.rs
// Module: euclid_wasm
// Public structs: 2

use euclid::frontend::dir::DirKeyKind;
#[cfg(feature = "payouts")]
use euclid::frontend::dir::PayoutDirKeyKind;
use serde::Serialize;

#[derive(Serialize, Clone)]
pub struct Details<'a> {
    pub description: Option<&'a str>,
    pub kind: DirKeyKind,
}

#[cfg(feature = "payouts")]
#[derive(Serialize, Clone)]
pub struct PayoutDetails<'a> {
    pub description: Option<&'a str>,
    pub kind: PayoutDirKeyKind,
}


        >(
            state.clone(),
            req_state,
            merchant_context.to_owned(),
            None,
            payments::PaymentConfirm,
            request,
            services::api::AuthFlow::Merchant,
            payments::CallConnectorAction::Trigger,
            None,
            HeaderPayload::with_source(common_enums::PaymentSource::Webhook),
        ))
        .await
    } else {
        Err(report!(
            errors::ApiErrorResponse::WebhookAuthenticationFailed
        ))
    };

    match response? {
        services::ApplicationResponse::JsonWithHeaders((payments_response, _)) => {
            let payment_id = payments_response.payment_id.clone();

            let event_type: Option<enums::EventType> = payments_response.status.into();
            let status = payments_response.status;

            // If event is NOT an UnsupportedEvent, trigger Outgoing Webhook
            if let Some(outgoing_event_type) = event_type {
                let primary_object_created_at = payments_response.created;
                Box::pin(super::create_event_and_trigger_outgoing_webhook(
                    state,
                    merchant_context,
                    business_profile,
                    outgoing_event_type,
                    enums::EventClass::Payments,
                    payment_id.get_string_repr().to_owned(),
                    enums::EventObjectType::PaymentDetails,
                    api::OutgoingWebhookContent::PaymentDetails(Box::new(payments_response)),
                    primary_object_created_at,
                ))
                .await?;
            }

            Ok(WebhookResponseTracker::Payment { payment_id, status })
        }

        _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure)
            .attach_printable("received non-json response from payments core")?,
    }
}

async fn get_payment_id(
    db: &dyn StorageInterface,
    payment_id: &api::PaymentIdType,
    merchant_id: &common_utils::id_type::MerchantId,
    storage_scheme: enums::MerchantStorageScheme,
) -> errors::RouterResult<common_utils::id_type::PaymentId> {
    let pay_id = || async {
        match payment_id {
            api_models::payments::PaymentIdType::PaymentIntentId(ref id) => Ok(id.to_owned()),
            api_models::payments::PaymentIdType::ConnectorTransactionId(ref id) => db
                .find_payment_attempt_by_merchant_id_connector_txn_id(
                    merchant_id,
                    id,
                    storage_scheme,
                )
                .await
                .map(|p| p.payment_id),
            api_models::payments::PaymentIdType::PaymentAttemptId(ref id) => db
                .find_payment_attempt_by_attempt_id_merchant_id(id, merchant_id, storage_scheme)
                .await
                .map(|p| p.payment_id),
            api_models::payments::PaymentIdType::PreprocessingId(ref id) => db
                .find_payment_attempt_by_preprocessing_id_merchant_id(
                    id,
                    merchant_id,
                    storage_scheme,
                )
                .await
                .map(|p| p.payment_id),
        }
    };

    pay_id()
        .await
        .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
}

#[inline]
async fn verify_webhook_source_verification_call(
    connector: ConnectorEnum,
    state: &SessionState,
    merchant_context: &domain::MerchantContext,
    merchant_connector_account: domain::MerchantConnectorAccount,
    connector_name: &str,
    request_details: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<bool, errors::ConnectorError> {
    let connector_data = ConnectorData::get_connector_by_name(
        &state.conf.connectors,
        connector_name,
        GetToken::Connector,
        None,
    )
    .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
    .attach_printable("invalid connector name received in payment attempt")?;
    let connector_integration: services::BoxedWebhookSourceVerificationConnectorIntegrationInterface<
        hyperswitch_domain_models::router_flow_types::VerifyWebhookSource,
        VerifyWebhookSourceRequestData,
        VerifyWebhookSourceResponseData,
    > = connector_data.connector.get_connector_integration();
    let connector_webhook_secrets = connector
        .get_webhook_source_verification_merchant_secret(
            merchant_context.get_merchant_account().get_id(),
            connector_name,
            merchant_connector_account.connector_webhook_details.clone(),
        )
        .await
        .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;

    let router_data = construct_webhook_router_data(
        state,
        connector_name,
        merchant_connector_account,
        merchant_context,
        &connector_webhook_secrets,
        request_details,
    )
    .await
    .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
    .attach_printable("Failed while constructing webhook router data")?;

    let response = services::execute_connector_processing_step(
        state,
        connector_integration,
        &router_data,
        payments::CallConnectorAction::Trigger,
        None,
        None,
    )
    .await?;

    let verification_result = response
        .response
        .map(|response| response.verify_webhook_status);
    match verification_result {
        Ok(VerifyWebhookStatus::SourceVerified) => Ok(true),
        _ => Ok(false),
    }
}

pub fn get_connector_by_connector_name(
    state: &SessionState,
    connector_name: &str,
    merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
) -> CustomResult<(ConnectorEnum, String), errors::ApiErrorResponse> {
    let authentication_connector =
        api_models::enums::convert_authentication_connector(connector_name);
    #[cfg(feature = "frm")]
    {
        let frm_connector = api_models::enums::convert_frm_connector(connector_name);
        if frm_connector.is_some() {
            let frm_connector_data =
                api::FraudCheckConnectorData::get_connector_by_name(connector_name)?;
            return Ok((
                frm_connector_data.connector,
                frm_connector_data.connector_name.to_string(),
            ));
        }
    }

    let (connector, connector_name) = if authentication_connector.is_some() {
        let authentication_connector_data =
            api::AuthenticationConnectorData::get_connector_by_name(connector_name)?;
        (
            authentication_connector_data.connector,
            authentication_connector_data.connector_name.to_string(),
        )
    } else {
        let connector_data = ConnectorData::get_connector_by_name(
            &state.conf.connectors,
            connector_name,
            GetToken::Connector,
            merchant_connector_id,
        )
        .change_context(errors::ApiErrorResponse::InvalidRequestData {
            message: "invalid connector name received".to_string(),
        })
        .attach_printable("Failed construction of ConnectorData")?;
        (
            connector_data.connector,
            connector_data.connector_name.to_string(),
        )
    };
    Ok((connector, connector_name))
}

/// This function fetches the merchant connector account ( if the url used is /{merchant_connector_id})
/// if merchant connector id is not passed in the request, then this will return None for mca
async fn fetch_optional_mca_and_connector(
    state: &SessionState,
    merchant_context: &domain::MerchantContext,
    connector_name_or_mca_id: &str,
) -> CustomResult<
    (
        Option<domain::MerchantConnectorAccount>,
        ConnectorEnum,
        String,
    ),
    errors::ApiErrorResponse,
> {
    let db = &state.store;
    if connector_name_or_mca_id.starts_with("mca_") {
        #[cfg(feature = "v1")]
        let mca = db
            .find_by_merchant_connector_account_merchant_id_merchant_connector_id(
                &state.into(),
                merchant_context.get_merchant_account().get_id(),
                &common_utils::id_type::MerchantConnectorAccountId::wrap(
                    connector_name_or_mca_id.to_owned(),
                )
                .change_context(errors::ApiErrorResponse::InternalServerError)
                .attach_printable(
                    "Error while converting MerchanConnectorAccountId from string
                    ",
                )?,
                merchant_context.get_merchant_key_store(),
            )
            .await
            .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
                id: connector_name_or_mca_id.to_string(),
            })
            .attach_printable(
                "error while fetching merchant_connector_account from connector_id",
            )?;

        #[cfg(feature = "v2")]
        let mca: domain::MerchantConnectorAccount = {
            let _ = merchant_account;
            let _ = key_store;
            let _ = db;
            todo!()
        };

        let (connector, connector_name) =
            get_connector_by_connector_name(state, &mca.connector_name, Some(mca.get_id()))?;

        Ok((Some(mca), connector, connector_name))
    } else {
        // Merchant connector account is already being queried, it is safe to set connector id as None
        let (connector, connector_name) =
            get_connector_by_connector_name(state, connector_name_or_mca_id, None)?;
        Ok((None, connector, connector_name))
    }
}

fn should_update_connector_mandate_details(
    source_verified: bool,
    event_type: webhooks::IncomingWebhookEvent,
) -> bool {
    source_verified && event_type == webhooks::IncomingWebhookEvent::PaymentIntentSuccess
}

async fn update_connector_mandate_details(
    state: &SessionState,
    merchant_context: &domain::MerchantContext,
    object_ref_id: api::ObjectReferenceId,
    connector: &ConnectorEnum,
    request_details: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<(), errors::ApiErrorResponse> {
    let webhook_connector_mandate_details = connector
        .get_mandate_details(request_details)
        .switch()
        .attach_printable("Could not find connector mandate details in incoming webhook body")?;

    let webhook_connector_network_transaction_id = connector
        .get_network_txn_id(request_details)
        .switch()
        .attach_printable(
            "Could not find connector network transaction id in incoming webhook body",
        )?;

    // Either one OR both of the fields are present
    if webhook_connector_mandate_details.is_some()
        || webhook_connector_network_transaction_id.is_some()
    {
        let payment_attempt =
            get_payment_attempt_from_object_reference_id(state, object_ref_id, merchant_context)
                .await?;
        if let Some(ref payment_method_id) = payment_attempt.payment_method_id {
            let key_manager_state = &state.into();
            let payment_method_info = state
                .store
                .find_payment_method(
                    key_manager_state,
                    merchant_context.get_merchant_key_store(),
                    payment_method_id,
                    merchant_context.get_merchant_account().storage_scheme,
                )
                .await
                .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;

            // Update connector's mandate details
            let updated_connector_mandate_details =
                if let Some(webhook_mandate_details) = webhook_connector_mandate_details {
                    let mandate_details = payment_method_info
                        .get_common_mandate_reference()
                        .change_context(errors::ApiErrorResponse::InternalServerError)
                        .attach_printable("Failed to deserialize to Payment Mandate Reference")?;

                    let merchant_connector_account_id = payment_attempt
                        .merchant_connector_id
                        .clone()
                        .get_required_value("merchant_connector_id")?;

                    if mandate_details.payments.as_ref().is_none_or(|payments| {
                        !payments.0.contains_key(&merchant_connector_account_id)
                    }) {
                        // Update the payment attempt to maintain consistency across tables.
                        let (mandate_metadata, connector_mandate_request_reference_id) =
                            payment_attempt
                                .connector_mandate_detail
                                .as_ref()
                                .map(|details| {
                                    (
                                        details.mandate_metadata.clone(),
                                        details.connector_mandate_request_reference_id.clone(),
                                    )
                                })
                                .unwrap_or((None, None));

                        let connector_mandate_reference_id = ConnectorMandateReferenceId {
                            connector_mandate_id: Some(
                                webhook_mandate_details
                                    .connector_mandate_id
                                    .peek()
                                    .to_string(),
                            ),
                            payment_method_id: Some(payment_method_id.to_string()),
                            mandate_metadata,
                            connector_mandate_request_reference_id,
                        };

                        let attempt_update =
                            storage::PaymentAttemptUpdate::ConnectorMandateDetailUpdate {
                                connector_mandate_detail: Some(connector_mandate_reference_id),
                                updated_by: merchant_context
                                    .get_merchant_account()
                                    .storage_scheme
                                    .to_string(),
                            };

                        state
                            .store
                            .update_payment_attempt_with_attempt_id(
                                payment_attempt.clone(),
                                attempt_update,
                                merchant_context.get_merchant_account().storage_scheme,
                            )
                            .await
                            .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;

                        insert_mandate_details(
                            &payment_attempt,
                            &webhook_mandate_details,
                            Some(mandate_details),
                        )?
                    } else {
                        logger::info!(
                        "Skipping connector mandate details update since they are already present."
                    );
                        None
                    }
                } else {
                    None
                };

            let connector_mandate_details_value = updated_connector_mandate_details
                .map(|common_mandate| {
                    common_mandate.get_mandate_details_value().map_err(|err| {
                        router_env::logger::error!(
                            "Failed to get get_mandate_details_value : {:?}",
                            err
                        );
                        errors::ApiErrorResponse::MandateUpdateFailed
                    })
                })
                .transpose()?;

            let pm_update = diesel_models::PaymentMethodUpdate::ConnectorNetworkTransactionIdAndMandateDetailsUpdate {
                connector_mandate_details: connector_mandate_details_value.map(masking::Secret::new),
                network_transaction_id: webhook_connector_network_transaction_id
                    .map(|webhook_network_transaction_id| webhook_network_transaction_id.get_id().clone()),
            };

            state
                .store
                .update_payment_method(
                    key_manager_state,
                    merchant_context.get_merchant_key_store(),
                    payment_method_info,
                    pm_update,
                    merchant_context.get_merchant_account().storage_scheme,
                )
                .await
                .change_context(errors::ApiErrorResponse::InternalServerError)
                .attach_printable("Failed to update payment method in db")?;
        }
    }
    Ok(())
}

fn insert_mandate_details(
    payment_attempt: &PaymentAttempt,
    webhook_mandate_details: &hyperswitch_domain_models::router_flow_types::ConnectorMandateDetails,
    payment_method_mandate_details: Option<CommonMandateReference>,
) -> CustomResult<Option<CommonMandateReference>, errors::ApiErrorResponse> {
    let (mandate_metadata, connector_mandate_request_reference_id) = payment_attempt
        .connector_mandate_detail
        .clone()
        .map(|mandate_reference| {
            (
                mandate_reference.mandate_metadata,
                mandate_reference.connector_mandate_request_reference_id,
            )
        })
        .unwrap_or((None, None));
    let connector_mandate_details = tokenization::update_connector_mandate_details(
        payment_method_mandate_details,
        payment_attempt.payment_method_type,
        Some(
            payment_attempt
                .net_amount
                .get_total_amount()
                .get_amount_as_i64(),
        ),
        payment_attempt.currency,
        payment_attempt.merchant_connector_id.clone(),
        Some(
            webhook_mandate_details
                .connector_mandate_id
                .peek()
                .to_string(),
        ),
        mandate_metadata,
        connector_mandate_request_reference_id,
    )?;
    Ok(connector_mandate_details)
}


// Struct: GooglePayMerchantInfo
// File: crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct GooglePayMerchantInfo


// Function: routing_retrieve_linked_config
// File: crates/openapi/src/routes/routing.rs
// Module: openapi

pub fn routing_retrieve_linked_config()


// Implementation: impl api::RefundSync for for Bamboraapac
// File: crates/hyperswitch_connectors/src/connectors/bamboraapac.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl api::RefundSync for for Bamboraapac


// Implementation: impl masking::SerializableSecret for for PaymentMethodType
// File: crates/common_enums/src/enums.rs
// Module: common_enums
// Methods: 0 total (0 public)

impl masking::SerializableSecret for for PaymentMethodType


// Trait: GenerateResponse
// File: crates/router/src/core/payments/transformers.rs
// Module: router

// Documentation: Generate a response from the given Data. This should be implemented on a payment data object

pub trait GenerateResponse<Response>


// Struct: WorldpayxmlRefundRequest
// File: crates/hyperswitch_connectors/src/connectors/worldpayxml/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct WorldpayxmlRefundRequest


// File: crates/hyperswitch_connectors/src/connectors/moneris.rs
// Module: hyperswitch_connectors
// Public functions: 1
// Public structs: 1

pub mod transformers;

use std::sync::LazyLock;

use common_enums::enums;
use common_utils::{
    errors::CustomResult,
    ext_traits::BytesExt,
    request::{Method, Request, RequestBuilder, RequestContent},
    types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
    router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
    router_flow_types::{
        access_token_auth::AccessTokenAuth,
        payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
        refunds::{Execute, RSync},
    },
    router_request_types::{
        AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
        PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
        RefundsData, SetupMandateRequestData,
    },
    router_response_types::{
        ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
        SupportedPaymentMethods, SupportedPaymentMethodsExt,
    },
    types::{
        PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
        PaymentsSyncRouterData, RefreshTokenRouterData, RefundSyncRouterData, RefundsRouterData,
    },
};
use hyperswitch_interfaces::{
    api::{
        self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
        ConnectorValidation,
    },
    configs::Connectors,
    errors,
    events::connector_api_logs::ConnectorEvent,
    types::{self, RefreshTokenType, Response},
    webhooks,
};
use masking::{ExposeInterface, Mask, PeekInterface};
use transformers as moneris;

use crate::{
    constants::headers,
    types::ResponseRouterData,
    utils::{self, is_mandate_supported, PaymentMethodDataType, RefundsRequestData},
};

#[derive(Clone)]
pub struct Moneris {
    amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}

impl Moneris {
    pub fn new() -> &'static Self {
        &Self {
            amount_converter: &MinorUnitForConnector,
        }
    }
}

impl api::Payment for Moneris {}
impl api::PaymentSession for Moneris {}
impl api::ConnectorAccessToken for Moneris {}
impl api::MandateSetup for Moneris {}
impl api::PaymentAuthorize for Moneris {}
impl api::PaymentSync for Moneris {}
impl api::PaymentCapture for Moneris {}
impl api::PaymentVoid for Moneris {}
impl api::Refund for Moneris {}
impl api::RefundExecute for Moneris {}
impl api::RefundSync for Moneris {}
impl api::PaymentToken for Moneris {}

impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
    for Moneris
{
    // Not Implemented (R)
}

impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Moneris
where
    Self: ConnectorIntegration<Flow, Request, Response>,
{
    fn build_headers(
        &self,
        req: &RouterData<Flow, Request, Response>,
        _connectors: &Connectors,
    ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
        let auth = moneris::MonerisAuthType::try_from(&req.connector_auth_type)
            .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
        let mut header = vec![
            (
                headers::CONTENT_TYPE.to_string(),
                self.get_content_type().to_string().into(),
            ),
            (
                moneris::auth_headers::API_VERSION.to_string(),
                "2024-09-17".to_string().into(),
            ),
            (
                moneris::auth_headers::X_MERCHANT_ID.to_string(),
                auth.merchant_id.expose().into_masked(),
            ),
        ];
        let access_token = req
            .access_token
            .clone()
            .ok_or(errors::ConnectorError::FailedToObtainAuthType)?;
        let auth_header = (
            headers::AUTHORIZATION.to_string(),
            format!("Bearer {}", access_token.token.peek()).into_masked(),
        );
        header.push(auth_header);
        Ok(header)
    }
}

impl ConnectorCommon for Moneris {
    fn id(&self) -> &'static str {
        "moneris"
    }

    fn get_currency_unit(&self) -> api::CurrencyUnit {
        api::CurrencyUnit::Minor
    }

    fn common_get_content_type(&self) -> &'static str {
        "application/json"
    }

    fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
        connectors.moneris.base_url.as_ref()
    }

    fn get_auth_header(
        &self,
        auth_type: &ConnectorAuthType,
    ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
        let auth = moneris::MonerisAuthType::try_from(auth_type)
            .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
        Ok(vec![(
            headers::AUTHORIZATION.to_string(),
            auth.client_id.expose().into_masked(),
        )])
    }

    fn build_error_response(
        &self,
        res: Response,
        event_builder: Option<&mut ConnectorEvent>,
    ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
        let response: moneris::MonerisErrorResponse = res
            .response
            .parse_struct("MonerisErrorResponse")
            .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;

        event_builder.map(|i| i.set_response_body(&response));
        router_env::logger::info!(connector_response=?response);

        let reason = match &response.errors {
            Some(error_list) => error_list
                .iter()
                .map(|error| error.parameter_name.clone())
                .collect::<Vec<String>>()
                .join(" & "),
            None => response.title.clone(),
        };

        Ok(ErrorResponse {
            status_code: res.status_code,
            code: response.category,
            message: response.title,
            reason: Some(reason),
            attempt_status: None,
            connector_transaction_id: None,
            network_advice_code: None,
            network_decline_code: None,
            network_error_message: None,
            connector_metadata: None,
        })
    }
}

impl ConnectorValidation for Moneris {
    fn validate_mandate_payment(
        &self,
        pm_type: Option<enums::PaymentMethodType>,
        pm_data: hyperswitch_domain_models::payment_method_data::PaymentMethodData,
    ) -> CustomResult<(), errors::ConnectorError> {
        let mandate_supported_pmd = std::collections::HashSet::from([PaymentMethodDataType::Card]);
        is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
    }
}

impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Moneris {
    //TODO: implement sessions flow
}

impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Moneris {
    fn get_url(
        &self,
        _req: &RefreshTokenRouterData,
        connectors: &Connectors,
    ) -> CustomResult<String, errors::ConnectorError> {
        Ok(format!("{}/oauth2/token", self.base_url(connectors)))
    }
    fn get_content_type(&self) -> &'static str {
        "application/x-www-form-urlencoded"
    }
    fn get_headers(
        &self,
        _req: &RefreshTokenRouterData,
        _connectors: &Connectors,
    ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
        Ok(vec![(
            headers::CONTENT_TYPE.to_string(),
            RefreshTokenType::get_content_type(self).to_string().into(),
        )])
    }

    fn get_request_body(
        &self,
        req: &RefreshTokenRouterData,
        _connectors: &Connectors,
    ) -> CustomResult<RequestContent, errors::ConnectorError> {
        let connector_req = moneris::MonerisAuthRequest::try_from(req)?;
        Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
    }

    fn build_request(
        &self,
        req: &RefreshTokenRouterData,
        connectors: &Connectors,
    ) -> CustomResult<Option<Request>, errors::ConnectorError> {
        let req = Some(
            RequestBuilder::new()
                .method(Method::Post)
                .attach_default_headers()
                .headers(RefreshTokenType::get_headers(self, req, connectors)?)
                .url(&RefreshTokenType::get_url(self, req, connectors)?)
                .set_body(RefreshTokenType::get_request_body(self, req, connectors)?)
                .build(),
        );
        Ok(req)
    }

    fn handle_response(
        &self,
        data: &RefreshTokenRouterData,
        event_builder: Option<&mut ConnectorEvent>,
        res: Response,
    ) -> CustomResult<RefreshTokenRouterData, errors::ConnectorError> {
        let response: moneris::MonerisAuthResponse = res
            .response
            .parse_struct("Moneris MonerisAuthResponse")
            .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;

        event_builder.map(|i| i.set_response_body(&response));
        router_env::logger::info!(connector_response=?response);

        RouterData::try_from(ResponseRouterData {
            response,
            data: data.clone(),
            http_code: res.status_code,
        })
    }

    fn get_error_response(
        &self,
        res: Response,
        event_builder: Option<&mut ConnectorEvent>,
    ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
        // auth error have different structure than common error
        let response: moneris::MonerisAuthErrorResponse = res
            .response
            .parse_struct("MonerisAuthErrorResponse")
            .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
        event_builder.map(|i| i.set_error_response_body(&response));
        router_env::logger::info!(connector_response=?response);
        Ok(ErrorResponse {
            status_code: res.status_code,
            code: response.error.to_string(),
            message: response.error.clone(),
            reason: response.error_description,
            attempt_status: None,
            connector_transaction_id: None,
            network_advice_code: None,
            network_decline_code: None,
            network_error_message: None,
            connector_metadata: None,
        })
    }
}

impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Moneris {
    // Not Implemented (R)
    fn build_request(
        &self,
        _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
        _connectors: &Connectors,
    ) -> CustomResult<Option<Request>, errors::ConnectorError> {
        Err(
            errors::ConnectorError::NotImplemented("Setup Mandate flow for Moneris".to_string())
                .into(),
        )
    }
}

impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Moneris {
    fn get_headers(
        &self,
        req: &PaymentsAuthorizeRouterData,
        connectors: &Connectors,
    ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
        self.build_headers(req, connectors)
    }

    fn get_content_type(&self) -> &'static str {
        self.common_get_content_type()
    }

    fn get_url(
        &self,
        _req: &PaymentsAuthorizeRouterData,
        connectors: &Connectors,
    ) -> CustomResult<String, errors::ConnectorError> {
        Ok(format!("{}/payments", self.base_url(connectors)))
    }

    fn get_request_body(
        &self,
        req: &PaymentsAuthorizeRouterData,
        _connectors: &Connectors,
    ) -> CustomResult<RequestContent, errors::ConnectorError> {
        let amount = utils::convert_amount(
            self.amount_converter,
            req.request.minor_amount,
            req.request.currency,
        )?;

        let connector_router_data = moneris::MonerisRouterData::from((amount, req));
        let connector_req = moneris::MonerisPaymentsRequest::try_from(&connector_router_data)?;
        Ok(RequestContent::Json(Box::new(connector_req)))
    }

    fn build_request(
        &self,
        req: &PaymentsAuthorizeRouterData,
        connectors: &Connectors,
    ) -> CustomResult<Option<Request>, errors::ConnectorError> {
        Ok(Some(
            RequestBuilder::new()
                .method(Method::Post)
                .url(&types::PaymentsAuthorizeType::get_url(
                    self, req, connectors,
                )?)
                .attach_default_headers()
                .headers(types::PaymentsAuthorizeType::get_headers(
                    self, req, connectors,
                )?)
                .set_body(types::PaymentsAuthorizeType::get_request_body(
                    self, req, connectors,
                )?)
                .build(),
        ))
    }

    fn handle_response(
        &self,
        data: &PaymentsAuthorizeRouterData,
        event_builder: Option<&mut ConnectorEvent>,
        res: Response,
    ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
        let response: moneris::MonerisPaymentsResponse = res
            .response
            .parse_struct("Moneris PaymentsAuthorizeResponse")
            .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
        event_builder.map(|i| i.set_response_body(&response));
        router_env::logger::info!(connector_response=?response);
        RouterData::try_from(ResponseRouterData {
            response,
            data: data.clone(),
            http_code: res.status_code,
        })
    }

    fn get_error_response(
        &self,
        res: Response,
        event_builder: Option<&mut ConnectorEvent>,
    ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
        self.build_error_response(res, event_builder)
    }
}

impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Moneris {
    fn get_headers(
        &self,
        req: &PaymentsSyncRouterData,
        connectors: &Connectors,
    ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
        self.build_headers(req, connectors)
    }

    fn get_content_type(&self) -> &'static str {
        self.common_get_content_type()
    }

    fn get_url(
        &self,
        req: &PaymentsSyncRouterData,
        connectors: &Connectors,
    ) -> CustomResult<String, errors::ConnectorError> {
        let connector_payment_id = req
            .request
            .connector_transaction_id
            .get_connector_transaction_id()
            .change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
        Ok(format!(
            "{}/payments/{connector_payment_id}",
            self.base_url(connectors)
        ))
    }

    fn build_request(
        &self,
        req: &PaymentsSyncRouterData,
        connectors: &Connectors,
    ) -> CustomResult<Option<Request>, errors::ConnectorError> {
        Ok(Some(
            RequestBuilder::new()
                .method(Method::Get)
                .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
                .attach_default_headers()
                .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
                .build(),
        ))
    }

    fn handle_response(
        &self,
        data: &PaymentsSyncRouterData,
        event_builder: Option<&mut ConnectorEvent>,
        res: Response,
    ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
        let response: moneris::MonerisPaymentsResponse = res
            .response
            .parse_struct("moneris PaymentsSyncResponse")
            .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
        event_builder.map(|i| i.set_response_body(&response));
        router_env::logger::info!(connector_response=?response);
        RouterData::try_from(ResponseRouterData {
            response,
            data: data.clone(),
            http_code: res.status_code,
        })
    }

    fn get_error_response(
        &self,
        res: Response,
        event_builder: Option<&mut ConnectorEvent>,
    ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
        self.build_error_response(res, event_builder)
    }
}

impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Moneris {
    fn get_headers(
        &self,
        req: &PaymentsCaptureRouterData,
        connectors: &Connectors,
    ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
        self.build_headers(req, connectors)
    }

    fn get_content_type(&self) -> &'static str {
        self.common_get_content_type()
    }

    fn get_url(
        &self,
        req: &PaymentsCaptureRouterData,
        connectors: &Connectors,
    ) -> CustomResult<String, errors::ConnectorError> {
        let connector_payment_id = req.request.connector_transaction_id.clone();
        Ok(format!(
            "{}/payments/{connector_payment_id}/complete",
            self.base_url(connectors)
        ))
    }

    fn get_request_body(
        &self,
        req: &PaymentsCaptureRouterData,
        _connectors: &Connectors,
    ) -> CustomResult<RequestContent, errors::ConnectorError> {
        let amount = utils::convert_amount(
            self.amount_converter,
            req.request.minor_amount_to_capture,
            req.request.currency,
        )?;

        let connector_router_data = moneris::MonerisRouterData::from((amount, req));
        let connector_req =
            moneris::MonerisPaymentsCaptureRequest::try_from(&connector_router_data)?;
        Ok(RequestContent::Json(Box::new(connector_req)))
    }

    fn build_request(
        &self,
        req: &PaymentsCaptureRouterData,
        connectors: &Connectors,
    ) -> CustomResult<Option<Request>, errors::ConnectorError> {
        Ok(Some(
            RequestBuilder::new()
                .method(Method::Post)
                .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
                .attach_default_headers()
                .headers(types::PaymentsCaptureType::get_headers(
                    self, req, connectors,
                )?)
                .set_body(types::PaymentsCaptureType::get_request_body(
                    self, req, connectors,
                )?)
                .build(),
        ))
    }

    fn handle_response(
        &self,
        data: &PaymentsCaptureRouterData,
        event_builder: Option<&mut ConnectorEvent>,
        res: Response,
    ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
        let response: moneris::MonerisPaymentsResponse = res
            .response
            .parse_struct("Moneris PaymentsCaptureResponse")
            .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
        event_builder.map(|i| i.set_response_body(&response));
        router_env::logger::info!(connector_response=?response);
        RouterData::try_from(ResponseRouterData {
            response,
            data: data.clone(),
            http_code: res.status_code,
        })
    }

    fn get_error_response(
        &self,
        res: Response,
        event_builder: Option<&mut ConnectorEvent>,
    ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
        self.build_error_response(res, event_builder)
    }
}

impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Moneris {
    fn get_headers(
        &self,
        req: &PaymentsCancelRouterData,
        connectors: &Connectors,
    ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
        self.build_headers(req, connectors)
    }

    fn get_content_type(&self) -> &'static str {
        self.common_get_content_type()
    }

    fn get_url(
        &self,
        req: &PaymentsCancelRouterData,
        connectors: &Connectors,
    ) -> CustomResult<String, errors::ConnectorError> {
        let connector_payment_id = req.request.connector_transaction_id.clone();
        Ok(format!(
            "{}/payments/{connector_payment_id}/cancel",
            self.base_url(connectors)
        ))
    }

    fn get_request_body(
        &self,
        req: &PaymentsCancelRouterData,
        _connectors: &Connectors,
    ) -> CustomResult<RequestContent, errors::ConnectorError> {
        let connector_req = moneris::MonerisCancelRequest::try_from(req)?;
        Ok(RequestContent::Json(Box::new(connector_req)))
    }

    fn build_request(
        &self,
        req: &PaymentsCancelRouterData,
        connectors: &Connectors,
    ) -> CustomResult<Option<Request>, errors::ConnectorError> {
        Ok(Some(
            RequestBuilder::new()
                .method(Method::Post)
                .url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
                .attach_default_headers()
                .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
                .set_body(types::PaymentsVoidType::get_request_body(
                    self, req, connectors,
                )?)
                .build(),
        ))
    }

    fn handle_response(
        &self,
        data: &PaymentsCancelRouterData,
        event_builder: Option<&mut ConnectorEvent>,
        res: Response,
    ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
        let response: moneris::MonerisPaymentsResponse = res
            .response
            .parse_struct("Moneris PaymentsCancelResponse")
            .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
        event_builder.map(|i| i.set_response_body(&response));
        router_env::logger::info!(connector_response=?response);
        RouterData::try_from(ResponseRouterData {
            response,
            data: data.clone(),
            http_code: res.status_code,
        })
    }
}

impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Moneris {
    fn get_headers(
        &self,
        req: &RefundsRouterData<Execute>,
        connectors: &Connectors,
    ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
        self.build_headers(req, connectors)
    }

    fn get_content_type(&self) -> &'static str {
        self.common_get_content_type()
    }

    fn get_url(
        &self,
        _req: &RefundsRouterData<Execute>,
        connectors: &Connectors,
    ) -> CustomResult<String, errors::ConnectorError> {
        Ok(format!("{}/refunds", self.base_url(connectors)))
    }

    fn get_request_body(
        &self,
        req: &RefundsRouterData<Execute>,
        _connectors: &Connectors,
    ) -> CustomResult<RequestContent, errors::ConnectorError> {
        let refund_amount = utils::convert_amount(
            self.amount_converter,
            req.request.minor_refund_amount,
            req.request.currency,
        )?;

        let connector_router_data = moneris::MonerisRouterData::from((refund_amount, req));
        let connector_req = moneris::MonerisRefundRequest::try_from(&connector_router_data)?;
        Ok(RequestContent::Json(Box::new(connector_req)))
    }

    fn build_request(
        &self,
        req: &RefundsRouterData<Execute>,
        connectors: &Connectors,
    ) -> CustomResult<Option<Request>, errors::ConnectorError> {
        let request = RequestBuilder::new()
            .method(Method::Post)
            .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
            .attach_default_headers()
            .headers(types::RefundExecuteType::get_headers(
                self, req, connectors,
            )?)
            .set_body(types::RefundExecuteType::get_request_body(
                self, req, connectors,
            )?)
            .build();
        Ok(Some(request))
    }

    fn handle_response(
        &self,
        data: &RefundsRouterData<Execute>,
        event_builder: Option<&mut ConnectorEvent>,
        res: Response,
    ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
        let response: moneris::RefundResponse = res
            .response
            .parse_struct("moneris RefundResponse")
            .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
        event_builder.map(|i| i.set_response_body(&response));
        router_env::logger::info!(connector_response=?response);
        RouterData::try_from(ResponseRouterData {
            response,
            data: data.clone(),
            http_code: res.status_code,
        })
    }

    fn get_error_response(
        &self,
        res: Response,
        event_builder: Option<&mut ConnectorEvent>,
    ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
        self.build_error_response(res, event_builder)
    }
}

impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Moneris {
    fn get_headers(
        &self,
        req: &RefundSyncRouterData,
        connectors: &Connectors,
    ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
        self.build_headers(req, connectors)
    }

    fn get_content_type(&self) -> &'static str {
        self.common_get_content_type()
    }

    fn get_url(
        &self,
        req: &RefundSyncRouterData,
        connectors: &Connectors,
    ) -> CustomResult<String, errors::ConnectorError> {
        let refund_id = req.request.get_connector_refund_id()?;
        Ok(format!("{}/refunds/{refund_id}", self.base_url(connectors)))
    }

    fn build_request(
        &self,
        req: &RefundSyncRouterData,
        connectors: &Connectors,
    ) -> CustomResult<Option<Request>, errors::ConnectorError> {
        Ok(Some(
            RequestBuilder::new()
                .method(Method::Get)
                .url(&types::RefundSyncType::get_url(self, req, connectors)?)
                .attach_default_headers()
                .headers(types::RefundSyncType::get_headers(self, req, connectors)?)
                .set_body(types::RefundSyncType::get_request_body(
                    self, req, connectors,
                )?)
                .build(),
        ))
    }

    fn handle_response(
        &self,
        data: &RefundSyncRouterData,
        event_builder: Option<&mut ConnectorEvent>,
        res: Response,
    ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
        let response: moneris::RefundResponse = res
            .response
            .parse_struct("moneris RefundSyncResponse")
            .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
        event_builder.map(|i| i.set_response_body(&response));
        router_env::logger::info!(connector_response=?response);
        RouterData::try_from(ResponseRouterData {
            response,
            data: data.clone(),
            http_code: res.status_code,
        })
    }

    fn get_error_response(
        &self,
        res: Response,
        event_builder: Option<&mut ConnectorEvent>,
    ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
        self.build_error_response(res, event_builder)
    }
}

#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Moneris {
    fn get_webhook_object_reference_id(
        &self,
        _request: &webhooks::IncomingWebhookRequestDetails<'_>,
    ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
        Err(report!(errors::ConnectorError::WebhooksNotImplemented))
    }

    fn get_webhook_event_type(
        &self,
        _request: &webhooks::IncomingWebhookRequestDetails<'_>,
    ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
        Err(report!(errors::ConnectorError::WebhooksNotImplemented))
    }

    fn get_webhook_resource_object(
        &self,
        _request: &webhooks::IncomingWebhookRequestDetails<'_>,
    ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
        Err(report!(errors::ConnectorError::WebhooksNotImplemented))
    }
}

static MONERIS_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| {
    let supported_capture_methods = vec![
        enums::CaptureMethod::Automatic,
        enums::CaptureMethod::Manual,
    ];

    let supported_card_network = vec![
        common_enums::CardNetwork::Mastercard,
        common_enums::CardNetwork::Visa,
        common_enums::CardNetwork::Interac,
        common_enums::CardNetwork::AmericanExpress,
        common_enums::CardNetwork::JCB,
        common_enums::CardNetwork::DinersClub,
        common_enums::CardNetwork::Discover,
        common_enums::CardNetwork::CartesBancaires,
        common_enums::CardNetwork::UnionPay,
    ];

    let mut moneris_supported_payment_methods = SupportedPaymentMethods::new();

    moneris_supported_payment_methods.add(
        enums::PaymentMethod::Card,
        enums::PaymentMethodType::Credit,
        PaymentMethodDetails {
            mandates: enums::FeatureStatus::Supported,
            refunds: enums::FeatureStatus::Supported,
            supported_capture_methods: supported_capture_methods.clone(),
            specific_features: Some(
                api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
                    api_models::feature_matrix::CardSpecificFeatures {
                        three_ds: common_enums::FeatureStatus::NotSupported,
                        no_three_ds: common_enums::FeatureStatus::Supported,
                        supported_card_networks: supported_card_network.clone(),
                    }
                }),
            ),
        },
    );

    moneris_supported_payment_methods.add(
        enums::PaymentMethod::Card,
        enums::PaymentMethodType::Debit,
        PaymentMethodDetails {
            mandates: enums::FeatureStatus::Supported,
            refunds: enums::FeatureStatus::Supported,
            supported_capture_methods: supported_capture_methods.clone(),
            specific_features: Some(
                api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
                    api_models::feature_matrix::CardSpecificFeatures {
                        three_ds: common_enums::FeatureStatus::NotSupported,
                        no_three_ds: common_enums::FeatureStatus::Supported,
                        supported_card_networks: supported_card_network.clone(),
                    }
                }),
            ),
        },
    );

    moneris_supported_payment_methods
});

static MONERIS_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
    display_name: "Moneris",
    description: "Moneris is Canada's top payment solutions provider, empowering businesses with innovative mobile, online & in-store solutions.",
    connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
    integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};

static MONERIS_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];

impl ConnectorSpecifications for Moneris {
    fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
        Some(&MONERIS_CONNECTOR_INFO)
    }

    fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
        Some(&*MONERIS_SUPPORTED_PAYMENT_METHODS)
    }

    fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
        Some(&MONERIS_SUPPORTED_WEBHOOK_FLOWS)
    }
}