pub mod transformers;

use std::sync::LazyLock;

use base64::Engine;
use common_types::payments::GpayTokenizationData;
use common_utils::{
    errors::CustomResult,
    ext_traits::BytesExt,
    request::{Method, Request, RequestBuilder, RequestContent, XmlConfig},
    types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
    payment_method_data::PaymentMethodData,
    router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
    router_flow_types::{
        access_token_auth::AccessTokenAuth,
        payments::{
            Authorize, Capture, CompleteAuthorize, PSync, PaymentMethodToken, Session,
            SetupMandate, Void,
        },
        refunds::{Execute, RSync},
        unified_authentication_service::PreAuthenticate,
    },
    router_request_types::{
        AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData,
        PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData,
        PaymentsPreAuthenticateData, PaymentsSessionData, PaymentsSyncData, RefundsData,
        SetupMandateRequestData,
    },
    router_response_types::{
        ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
        SupportedPaymentMethods, SupportedPaymentMethodsExt,
    },
    types::{
        PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
        PaymentsCompleteAuthorizeRouterData, PaymentsPreAuthenticateRouterData,
        PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, SetupMandateRouterData,
    },
};
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::{
    router_flow_types::{
        payouts::{PoCancel, PoFulfill},
        PoSync,
    },
    router_request_types::PayoutsData,
    router_response_types::PayoutsResponseData,
    types::PayoutsRouterData,
};
use hyperswitch_interfaces::{
    api::{
        self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
        ConnectorValidation,
    },
    configs::Connectors,
    consts, errors,
    events::connector_api_logs::ConnectorEvent,
    types::{self, Response},
    webhooks,
};
use hyperswitch_masking::{ExposeInterface, Mask};
use transformers as worldpayxml;

use crate::{
    constants::headers,
    types::ResponseRouterData,
    utils::{self, ForeignTryFrom, PaymentsCompleteAuthorizeRequestData},
};

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

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

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

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

impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Worldpayxml
where
    Self: ConnectorIntegration<Flow, Request, Response>,
{
    fn build_headers(
        &self,
        req: &RouterData<Flow, Request, Response>,
        _connectors: &Connectors,
    ) -> CustomResult<Vec<(String, hyperswitch_masking::Maskable<String>)>, errors::ConnectorError>
    {
        let mut header = vec![(
            headers::CONTENT_TYPE.to_string(),
            self.common_get_content_type().to_string().into(),
        )];
        let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
        header.append(&mut api_key);
        Ok(header)
    }
}

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

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

    fn common_get_content_type(&self) -> &'static str {
        "text/xml"
    }

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

    fn get_auth_header(
        &self,
        auth_type: &ConnectorAuthType,
    ) -> CustomResult<Vec<(String, hyperswitch_masking::Maskable<String>)>, errors::ConnectorError>
    {
        let auth = worldpayxml::WorldpayxmlAuthType::try_from(auth_type)
            .change_context(errors::ConnectorError::FailedToObtainAuthType)?;

        let basic_auth_value = format!(
            "Basic {}",
            common_utils::consts::BASE64_ENGINE.encode(format!(
                "{}:{}",
                auth.api_username.expose(),
                auth.api_password.expose()
            ))
        );

        Ok(vec![(
            headers::AUTHORIZATION.to_string(),
            Mask::into_masked(basic_auth_value),
        )])
    }

    fn build_error_response(
        &self,
        res: Response,
        event_builder: Option<&mut ConnectorEvent>,
    ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
        if res.response.is_empty() {
            return Ok(ErrorResponse {
                status_code: res.status_code,
                code: consts::NO_ERROR_CODE.to_string(),
                message: consts::NO_ERROR_MESSAGE.to_string(),
                reason: None,
                attempt_status: None,
                connector_transaction_id: None,
                connector_response_reference_id: None,
                network_advice_code: None,
                network_decline_code: None,
                network_error_message: None,
                connector_metadata: None,
            });
        }

        let response: Result<worldpayxml::PaymentService, _> =
            utils::deserialize_xml_to_struct(&res.response);

        match response {
            Ok(response_data) => {
                event_builder.map(|i| i.set_error_response_body(&response_data));
                router_env::logger::info!(connector_response=?response_data);
                let (error_code, error_msg) = response_data
                    .reply
                    .as_ref()
                    .and_then(|reply| {
                        reply
                            .error
                            .as_ref()
                            .map(|error| (Some(error.code.clone()), Some(error.message.clone())))
                    })
                    .unwrap_or((None, None));

                Ok(ErrorResponse {
                    status_code: res.status_code,
                    code: error_code.unwrap_or(consts::NO_ERROR_CODE.to_string()),
                    message: error_msg
                        .clone()
                        .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
                    reason: error_msg.clone(),
                    attempt_status: None,
                    connector_transaction_id: None,
                    connector_response_reference_id: None,
                    network_advice_code: None,
                    network_decline_code: None,
                    network_error_message: None,
                    connector_metadata: None,
                })
            }
            Err(error_msg) => {
                event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code})));
                router_env::logger::error!(deserialization_error =? error_msg);
                utils::handle_json_response_deserialization_failure(res, "worldpayxml")
            }
        }
    }
}

impl ConnectorValidation for Worldpayxml {}

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

impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Worldpayxml {}

impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
    for Worldpayxml
{
    fn get_headers(
        &self,
        req: &SetupMandateRouterData,
        connectors: &Connectors,
    ) -> CustomResult<Vec<(String, hyperswitch_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: &SetupMandateRouterData,
        connectors: &Connectors,
    ) -> CustomResult<String, errors::ConnectorError> {
        Ok(self.base_url(connectors).to_owned())
    }

    fn get_request_body(
        &self,
        req: &SetupMandateRouterData,
        _connectors: &Connectors,
    ) -> CustomResult<RequestContent, errors::ConnectorError> {
        if req.request.amount > 0 {
            return Err(errors::ConnectorError::FlowNotSupported {
                flow: "Setup Mandate with non zero amount".to_string(),
                connector: "WorldpayWPG".to_string(),
            }
            .into());
        }

        match req.payment_method_type {
            Some(common_enums::PaymentMethodType::GooglePay)
            | Some(common_enums::PaymentMethodType::ApplePay) => {
                let authorize_req = utils::convert_payment_authorize_router_response((
                    req,
                    utils::convert_setup_mandate_router_data_to_authorize_router_data(req),
                ));

                let amount = utils::convert_amount(
                    self.amount_converter,
                    authorize_req.request.minor_amount,
                    authorize_req.request.currency,
                )?;

                let connector_router_data =
                    worldpayxml::WorldpayxmlRouterData::from((amount, &authorize_req));
                let connector_req_object =
                    worldpayxml::PaymentService::try_from(&connector_router_data)?;
                router_env::logger::info!(raw_connector_request=?connector_req_object);

                let xml_config = XmlConfig {
                    xml_version: worldpayxml::worldpayxml_constants::XML_VERSION.to_string(),
                    xml_encoding: Some(
                        worldpayxml::worldpayxml_constants::XML_ENCODING.to_string(),
                    ),
                    xml_standalone: None,
                    xml_doc_type: Some(
                        worldpayxml::worldpayxml_constants::WORLDPAYXML_DOC_TYPE.to_string(),
                    ),
                };
                Ok(RequestContent::Xml(
                    Box::new(connector_req_object),
                    Some(xml_config),
                ))
            }
            _ => Err(errors::ConnectorError::FlowNotSupported {
                flow: "Setup Mandate flow is not implemented for this payment method".to_string(),
                connector: "WorldpayWPG".to_string(),
            }
            .into()),
        }
    }

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

    fn handle_response(
        &self,
        data: &SetupMandateRouterData,
        event_builder: Option<&mut ConnectorEvent>,
        res: Response,
    ) -> CustomResult<SetupMandateRouterData, errors::ConnectorError> {
        let response: worldpayxml::PaymentService =
            utils::deserialize_xml_to_struct(&res.response)?;
        event_builder.map(|i| i.set_response_body(&response));
        router_env::logger::info!(connector_response=?response);
        SetupMandateRouterData::try_from(ResponseRouterData {
            response,
            data: data.clone(),
            http_code: res.status_code,
        })
    }
}

impl ConnectorIntegration<PreAuthenticate, PaymentsPreAuthenticateData, PaymentsResponseData>
    for Worldpayxml
{
    fn handle_response(
        &self,
        data: &PaymentsPreAuthenticateRouterData,
        _event_builder: Option<&mut ConnectorEvent>,
        res: Response,
    ) -> CustomResult<PaymentsPreAuthenticateRouterData, errors::ConnectorError> {
        RouterData::try_from(ResponseRouterData {
            response: res.response,
            data: data.clone(),
            http_code: res.status_code,
        })
    }
}

impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Worldpayxml {
    fn get_headers(
        &self,
        req: &PaymentsAuthorizeRouterData,
        connectors: &Connectors,
    ) -> CustomResult<Vec<(String, hyperswitch_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(self.base_url(connectors).to_owned())
    }

    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 = worldpayxml::WorldpayxmlRouterData::from((amount, req));
        let connector_req_object = worldpayxml::PaymentService::try_from(&connector_router_data)?;
        router_env::logger::info!(raw_connector_request=?connector_req_object);

        let xml_config = XmlConfig {
            xml_version: worldpayxml::worldpayxml_constants::XML_VERSION.to_string(),
            xml_encoding: Some(worldpayxml::worldpayxml_constants::XML_ENCODING.to_string()),
            xml_standalone: None,
            xml_doc_type: Some(
                worldpayxml::worldpayxml_constants::WORLDPAYXML_DOC_TYPE.to_string(),
            ),
        };
        Ok(RequestContent::Xml(
            Box::new(connector_req_object),
            Some(xml_config),
        ))
    }

    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 header = res.headers;
        let response: worldpayxml::PaymentService =
            utils::deserialize_xml_to_struct(&res.response)?;
        event_builder.map(|i| i.set_response_body(&response));
        router_env::logger::info!(connector_response=?response);
        RouterData::foreign_try_from((
            ResponseRouterData {
                response,
                data: data.clone(),
                http_code: res.status_code,
            },
            header,
        ))
    }

    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 Worldpayxml {
    fn get_headers(
        &self,
        req: &PaymentsSyncRouterData,
        connectors: &Connectors,
    ) -> CustomResult<Vec<(String, hyperswitch_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> {
        Ok(self.base_url(connectors).to_owned())
    }

    fn get_request_body(
        &self,
        req: &PaymentsSyncRouterData,
        _connectors: &Connectors,
    ) -> CustomResult<RequestContent, errors::ConnectorError> {
        let connector_req_object = worldpayxml::PaymentService::try_from(req)?;
        router_env::logger::info!(raw_connector_request=?connector_req_object);
        let xml_config = XmlConfig {
            xml_version: worldpayxml::worldpayxml_constants::XML_VERSION.to_string(),
            xml_encoding: Some(worldpayxml::worldpayxml_constants::XML_ENCODING.to_string()),
            xml_standalone: None,
            xml_doc_type: Some(
                worldpayxml::worldpayxml_constants::WORLDPAYXML_DOC_TYPE.to_string(),
            ),
        };
        Ok(RequestContent::Xml(
            Box::new(connector_req_object),
            Some(xml_config),
        ))
    }

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

    fn handle_response(
        &self,
        data: &PaymentsSyncRouterData,
        event_builder: Option<&mut ConnectorEvent>,
        res: Response,
    ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
        let response: worldpayxml::WorldpayxmlSyncResponse = match utils::deserialize_xml_to_struct::<
            worldpayxml::PaymentService,
        >(&res.response)
        {
            Ok(parsed_xml) => worldpayxml::WorldpayxmlSyncResponse::Payment(Box::new(parsed_xml)),
            Err(_) => res
                .response
                .parse_struct("worldpayxml WorldpayxmlSyncResponse")
                .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 Worldpayxml {
    fn get_headers(
        &self,
        req: &PaymentsCaptureRouterData,
        connectors: &Connectors,
    ) -> CustomResult<Vec<(String, hyperswitch_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> {
        Ok(self.base_url(connectors).to_owned())
    }

    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 = worldpayxml::WorldpayxmlRouterData::from((amount, req));
        let connector_req_object = worldpayxml::PaymentService::try_from(&connector_router_data)?;
        router_env::logger::info!(raw_connector_request=?connector_req_object);

        let xml_config = XmlConfig {
            xml_version: worldpayxml::worldpayxml_constants::XML_VERSION.to_string(),
            xml_encoding: Some(worldpayxml::worldpayxml_constants::XML_ENCODING.to_string()),
            xml_standalone: None,
            xml_doc_type: Some(
                worldpayxml::worldpayxml_constants::WORLDPAYXML_DOC_TYPE.to_string(),
            ),
        };
        Ok(RequestContent::Xml(
            Box::new(connector_req_object),
            Some(xml_config),
        ))
    }

    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: worldpayxml::PaymentService =
            utils::deserialize_xml_to_struct(&res.response)?;
        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 Worldpayxml {
    fn get_headers(
        &self,
        req: &PaymentsCancelRouterData,
        connectors: &Connectors,
    ) -> CustomResult<Vec<(String, hyperswitch_masking::Maskable<String>)>, errors::ConnectorError>
    {
        self.build_headers(req, connectors)
    }

    fn get_url(
        &self,
        _req: &PaymentsCancelRouterData,
        connectors: &Connectors,
    ) -> CustomResult<String, errors::ConnectorError> {
        Ok(self.base_url(connectors).to_owned())
    }

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

    fn get_request_body(
        &self,
        req: &PaymentsCancelRouterData,
        _connectors: &Connectors,
    ) -> CustomResult<RequestContent, errors::ConnectorError> {
        let connector_req_object = worldpayxml::PaymentService::try_from(req)?;
        router_env::logger::info!(raw_connector_request=?connector_req_object);

        let xml_config = XmlConfig {
            xml_version: worldpayxml::worldpayxml_constants::XML_VERSION.to_string(),
            xml_encoding: Some(worldpayxml::worldpayxml_constants::XML_ENCODING.to_string()),
            xml_standalone: None,
            xml_doc_type: Some(
                worldpayxml::worldpayxml_constants::WORLDPAYXML_DOC_TYPE.to_string(),
            ),
        };
        Ok(RequestContent::Xml(
            Box::new(connector_req_object),
            Some(xml_config),
        ))
    }

    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(self.get_request_body(req, connectors)?)
                .build(),
        ))
    }

    fn handle_response(
        &self,
        data: &PaymentsCancelRouterData,
        event_builder: Option<&mut ConnectorEvent>,
        res: Response,
    ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
        let response: worldpayxml::PaymentService =
            utils::deserialize_xml_to_struct(&res.response)?;
        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<Execute, RefundsData, RefundsResponseData> for Worldpayxml {
    fn get_headers(
        &self,
        req: &RefundsRouterData<Execute>,
        connectors: &Connectors,
    ) -> CustomResult<Vec<(String, hyperswitch_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(self.base_url(connectors).to_owned())
    }

    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 = worldpayxml::WorldpayxmlRouterData::from((refund_amount, req));
        let connector_req_object = worldpayxml::PaymentService::try_from(&connector_router_data)?;
        router_env::logger::info!(raw_connector_request=?connector_req_object);
        let xml_config = XmlConfig {
            xml_version: worldpayxml::worldpayxml_constants::XML_VERSION.to_string(),
            xml_encoding: Some(worldpayxml::worldpayxml_constants::XML_ENCODING.to_string()),
            xml_standalone: None,
            xml_doc_type: Some(
                worldpayxml::worldpayxml_constants::WORLDPAYXML_DOC_TYPE.to_string(),
            ),
        };
        Ok(RequestContent::Xml(
            Box::new(connector_req_object),
            Some(xml_config),
        ))
    }

    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: worldpayxml::PaymentService =
            utils::deserialize_xml_to_struct(&res.response)?;
        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 Worldpayxml {
    fn get_headers(
        &self,
        req: &RefundSyncRouterData,
        connectors: &Connectors,
    ) -> CustomResult<Vec<(String, hyperswitch_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> {
        Ok(self.base_url(connectors).to_owned())
    }

    fn get_request_body(
        &self,
        req: &RefundSyncRouterData,
        _connectors: &Connectors,
    ) -> CustomResult<RequestContent, errors::ConnectorError> {
        let connector_req_object = worldpayxml::PaymentService::try_from(req)?;
        router_env::logger::info!(raw_connector_request=?connector_req_object);

        let xml_config = XmlConfig {
            xml_version: worldpayxml::worldpayxml_constants::XML_VERSION.to_string(),
            xml_encoding: Some(worldpayxml::worldpayxml_constants::XML_ENCODING.to_string()),
            xml_standalone: None,
            xml_doc_type: Some(
                worldpayxml::worldpayxml_constants::WORLDPAYXML_DOC_TYPE.to_string(),
            ),
        };
        Ok(RequestContent::Xml(
            Box::new(connector_req_object),
            Some(xml_config),
        ))
    }

    fn build_request(
        &self,
        req: &RefundSyncRouterData,
        connectors: &Connectors,
    ) -> CustomResult<Option<Request>, errors::ConnectorError> {
        Ok(Some(
            RequestBuilder::new()
                .method(Method::Post)
                .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: worldpayxml::WorldpayxmlSyncResponse = match utils::deserialize_xml_to_struct::<
            worldpayxml::PaymentService,
        >(&res.response)
        {
            Ok(parsed_xml) => worldpayxml::WorldpayxmlSyncResponse::Payment(Box::new(parsed_xml)),
            Err(_) => res
                .response
                .parse_struct("worldpayxml WorldpayxmlSyncResponse")
                .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<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
    for Worldpayxml
{
    fn get_headers(
        &self,
        req: &PaymentsCompleteAuthorizeRouterData,
        connectors: &Connectors,
    ) -> CustomResult<Vec<(String, hyperswitch_masking::Maskable<String>)>, errors::ConnectorError>
    {
        let mut header = self.build_headers(req, connectors)?;
        if req
            .request
            .get_redirect_response_payload()
            .ok()
            .and_then(|response| {
                serde_json::from_value::<worldpayxml::WorldpayxmlRedirectionResponse>(
                    response.expose(),
                )
                .ok()
            })
            .is_some()
        {
            let cookie = worldpayxml::get_cookie_from_metadata(req.request.connector_meta.clone())?;

            let mut cookie = vec![(
                worldpayxml::worldpayxml_constants::COOKIE.to_string(),
                Mask::into_masked(cookie),
            )];

            header.append(&mut cookie);
        }
        Ok(header)
    }

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

    fn get_url(
        &self,
        _req: &PaymentsCompleteAuthorizeRouterData,
        connectors: &Connectors,
    ) -> CustomResult<String, errors::ConnectorError> {
        Ok(self.base_url(connectors).to_owned())
    }

    fn get_request_body(
        &self,
        req: &PaymentsCompleteAuthorizeRouterData,
        _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 = worldpayxml::WorldpayxmlRouterData::from((amount, req));

        let connector_req_object = worldpayxml::PaymentService::try_from(connector_router_data)?;
        router_env::logger::info!(raw_connector_request=?connector_req_object);
        let xml_config = XmlConfig {
            xml_version: worldpayxml::worldpayxml_constants::XML_VERSION.to_string(),
            xml_encoding: Some(worldpayxml::worldpayxml_constants::XML_ENCODING.to_string()),
            xml_standalone: None,
            xml_doc_type: Some(
                worldpayxml::worldpayxml_constants::WORLDPAYXML_DOC_TYPE.to_string(),
            ),
        };
        Ok(RequestContent::Xml(
            Box::new(connector_req_object),
            Some(xml_config),
        ))
    }

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

    fn handle_response(
        &self,
        data: &PaymentsCompleteAuthorizeRouterData,
        event_builder: Option<&mut ConnectorEvent>,
        res: Response,
    ) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
        let header = res.headers;
        let response: worldpayxml::PaymentService =
            utils::deserialize_xml_to_struct(&res.response)?;
        event_builder.map(|i| i.set_response_body(&response));
        router_env::logger::info!(connector_response=?response);
        RouterData::foreign_try_from((
            ResponseRouterData {
                response,
                data: data.clone(),
                http_code: res.status_code,
            },
            header,
        ))
    }

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

impl api::Payouts for Worldpayxml {}
#[cfg(feature = "payouts")]
impl api::PayoutFulfill for Worldpayxml {}
#[cfg(feature = "payouts")]
impl api::PayoutCancel for Worldpayxml {}
#[cfg(feature = "payouts")]
impl api::PayoutSync for Worldpayxml {}

#[async_trait::async_trait]
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> for Worldpayxml {
    fn get_url(
        &self,
        _req: &PayoutsRouterData<PoFulfill>,
        connectors: &Connectors,
    ) -> CustomResult<String, errors::ConnectorError> {
        Ok(self.base_url(connectors).to_owned())
    }

    fn get_headers(
        &self,
        req: &PayoutsRouterData<PoFulfill>,
        connectors: &Connectors,
    ) -> CustomResult<Vec<(String, hyperswitch_masking::Maskable<String>)>, errors::ConnectorError>
    {
        self.build_headers(req, connectors)
    }

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

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

        let connector_router_data = worldpayxml::WorldpayxmlRouterData::from((amount, req));

        let connector_req_object = worldpayxml::PaymentService::try_from(&connector_router_data)?;

        let xml_config = XmlConfig {
            xml_version: worldpayxml::worldpayxml_constants::XML_VERSION.to_string(),
            xml_encoding: Some(worldpayxml::worldpayxml_constants::XML_ENCODING.to_string()),
            xml_standalone: None,
            xml_doc_type: Some(
                worldpayxml::worldpayxml_constants::WORLDPAYXML_DOC_TYPE.to_string(),
            ),
        };
        Ok(RequestContent::Xml(
            Box::new(connector_req_object),
            Some(xml_config),
        ))
    }

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

    fn handle_response(
        &self,
        data: &PayoutsRouterData<PoFulfill>,
        event_builder: Option<&mut ConnectorEvent>,
        res: Response,
    ) -> CustomResult<PayoutsRouterData<PoFulfill>, errors::ConnectorError> {
        let response: worldpayxml::PayoutResponse =
            utils::deserialize_xml_to_struct(&res.response)?;
        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,
        })
        .change_context(errors::ConnectorError::ResponseHandlingFailed)
    }

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

    fn get_5xx_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]
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoSync, PayoutsData, PayoutsResponseData> for Worldpayxml {
    fn get_url(
        &self,
        _req: &PayoutsRouterData<PoSync>,
        connectors: &Connectors,
    ) -> CustomResult<String, errors::ConnectorError> {
        Ok(self.base_url(connectors).to_owned())
    }

    fn get_headers(
        &self,
        req: &PayoutsRouterData<PoSync>,
        connectors: &Connectors,
    ) -> CustomResult<Vec<(String, hyperswitch_masking::Maskable<String>)>, errors::ConnectorError>
    {
        self.build_headers(req, connectors)
    }

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

    fn get_request_body(
        &self,
        req: &PayoutsRouterData<PoSync>,
        _connectors: &Connectors,
    ) -> CustomResult<RequestContent, errors::ConnectorError> {
        let connector_req_object = worldpayxml::PaymentService::try_from(req)?;
        let xml_config = XmlConfig {
            xml_version: worldpayxml::worldpayxml_constants::XML_VERSION.to_string(),
            xml_encoding: Some(worldpayxml::worldpayxml_constants::XML_ENCODING.to_string()),
            xml_standalone: None,
            xml_doc_type: Some(
                worldpayxml::worldpayxml_constants::WORLDPAYXML_DOC_TYPE.to_string(),
            ),
        };
        Ok(RequestContent::Xml(
            Box::new(connector_req_object),
            Some(xml_config),
        ))
    }

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

    fn handle_response(
        &self,
        data: &PayoutsRouterData<PoSync>,
        event_builder: Option<&mut ConnectorEvent>,
        res: Response,
    ) -> CustomResult<PayoutsRouterData<PoSync>, errors::ConnectorError> {
        let response: worldpayxml::PaymentService =
            utils::deserialize_xml_to_struct(&res.response)?;
        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,
        })
        .change_context(errors::ConnectorError::ResponseHandlingFailed)
    }

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

    fn get_5xx_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]
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoCancel, PayoutsData, PayoutsResponseData> for Worldpayxml {
    fn get_url(
        &self,
        _req: &PayoutsRouterData<PoCancel>,
        connectors: &Connectors,
    ) -> CustomResult<String, errors::ConnectorError> {
        Ok(self.base_url(connectors).to_owned())
    }

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

    fn get_headers(
        &self,
        req: &PayoutsRouterData<PoCancel>,
        connectors: &Connectors,
    ) -> CustomResult<Vec<(String, hyperswitch_masking::Maskable<String>)>, errors::ConnectorError>
    {
        self.build_headers(req, connectors)
    }

    fn get_request_body(
        &self,
        req: &PayoutsRouterData<PoCancel>,
        _connectors: &Connectors,
    ) -> CustomResult<RequestContent, errors::ConnectorError> {
        let connector_req_object = worldpayxml::PaymentService::try_from(req)?;

        let xml_config = XmlConfig {
            xml_version: worldpayxml::worldpayxml_constants::XML_VERSION.to_string(),
            xml_encoding: Some(worldpayxml::worldpayxml_constants::XML_ENCODING.to_string()),
            xml_standalone: None,
            xml_doc_type: Some(
                worldpayxml::worldpayxml_constants::WORLDPAYXML_DOC_TYPE.to_string(),
            ),
        };
        Ok(RequestContent::Xml(
            Box::new(connector_req_object),
            Some(xml_config),
        ))
    }

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

    fn handle_response(
        &self,
        data: &PayoutsRouterData<PoCancel>,
        event_builder: Option<&mut ConnectorEvent>,
        res: Response,
    ) -> CustomResult<PayoutsRouterData<PoCancel>, errors::ConnectorError> {
        let response: worldpayxml::PayoutResponse =
            utils::deserialize_xml_to_struct(&res.response)?;
        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,
        })
        .change_context(errors::ConnectorError::ResponseHandlingFailed)
    }

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

    fn get_5xx_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 Worldpayxml {
    async fn verify_webhook_source(
        &self,
        _request: &webhooks::IncomingWebhookRequestDetails<'_>,
        _merchant_id: &common_utils::id_type::MerchantId,
        _connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
        _connector_account_details: common_utils::crypto::Encryptable<
            hyperswitch_masking::Secret<serde_json::Value>,
        >,
        _connector_label: &str,
    ) -> CustomResult<bool, errors::ConnectorError> {
        // Bypass Source Verification since it is done via MTLS
        Ok(true)
    }

    fn get_webhook_object_reference_id(
        &self,
        request: &webhooks::IncomingWebhookRequestDetails<'_>,
    ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
        let body_str = std::str::from_utf8(request.body)
            .map_err(|_| errors::ConnectorError::WebhookBodyDecodingFailed)?;

        let body: worldpayxml::WorldpayFormWebhookBody = serde_urlencoded::from_str(body_str)
            .map_err(|_| errors::ConnectorError::WebhookBodyDecodingFailed)?;
        let order_code = body.order_code.clone();
        if worldpayxml::is_refund_event(body.payment_status) {
            return Ok(api_models::webhooks::ObjectReferenceId::RefundId(
                api_models::webhooks::RefundIdType::ConnectorRefundId(order_code),
            ));
        }
        if worldpayxml::is_transaction_event(body.payment_status) {
            return Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
                api_models::payments::PaymentIdType::ConnectorTransactionId(order_code),
            ));
        }
        #[cfg(feature = "payouts")]
        if worldpayxml::is_payout_event(body.payment_status) {
            return Ok(api_models::webhooks::ObjectReferenceId::PayoutId(
                api_models::webhooks::PayoutIdType::ConnectorPayoutId(order_code),
            ));
        }
        Err(report!(errors::ConnectorError::WebhookReferenceIdNotFound))
    }

    fn get_webhook_event_type(
        &self,
        request: &webhooks::IncomingWebhookRequestDetails<'_>,
        _context: Option<&webhooks::WebhookContext>,
    ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
        if request.body.is_empty() {
            return Ok(api_models::webhooks::IncomingWebhookEvent::EndpointVerification);
        }

        let body_str = std::str::from_utf8(request.body)
            .map_err(|_| errors::ConnectorError::WebhookBodyDecodingFailed)?;

        let webhook_body: worldpayxml::WorldpayFormWebhookBody =
            serde_urlencoded::from_str(body_str)
                .map_err(|_| errors::ConnectorError::WebhookBodyDecodingFailed)?;

        #[cfg(feature = "payouts")]
        {
            if worldpayxml::is_payout_event(webhook_body.payment_status) {
                return Ok(worldpayxml::get_payout_webhook_event(
                    webhook_body.payment_status,
                ));
            }
        }

        Ok(worldpayxml::get_payment_webhook_event(
            webhook_body.payment_status,
        ))
    }

    fn get_webhook_resource_object(
        &self,
        request: &webhooks::IncomingWebhookRequestDetails<'_>,
    ) -> CustomResult<Box<dyn hyperswitch_masking::ErasedMaskSerialize>, errors::ConnectorError>
    {
        let body_str = std::str::from_utf8(request.body)
            .map_err(|_| errors::ConnectorError::WebhookBodyDecodingFailed)?;

        let body: worldpayxml::WorldpayFormWebhookBody = serde_urlencoded::from_str(body_str)
            .map_err(|_| errors::ConnectorError::WebhookBodyDecodingFailed)?;

        Ok(Box::new(body))
    }
}

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

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

        let mut worldpayxml_supported_payment_methods = SupportedPaymentMethods::new();

        worldpayxml_supported_payment_methods.add(
            common_enums::PaymentMethod::Card,
            common_enums::PaymentMethodType::Credit,
            PaymentMethodDetails {
                mandates: common_enums::FeatureStatus::NotSupported,
                refunds: common_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::Supported,
                            no_three_ds: common_enums::FeatureStatus::Supported,
                            supported_card_networks: supported_card_network.clone(),
                        }
                    }),
                ),
            },
        );

        worldpayxml_supported_payment_methods.add(
            common_enums::PaymentMethod::Card,
            common_enums::PaymentMethodType::Debit,
            PaymentMethodDetails {
                mandates: common_enums::FeatureStatus::NotSupported,
                refunds: common_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::Supported,
                            no_three_ds: common_enums::FeatureStatus::Supported,
                            supported_card_networks: supported_card_network.clone(),
                        }
                    }),
                ),
            },
        );

        worldpayxml_supported_payment_methods.add(
            common_enums::PaymentMethod::Wallet,
            common_enums::PaymentMethodType::GooglePay,
            PaymentMethodDetails {
                mandates: common_enums::FeatureStatus::Supported,
                refunds: common_enums::FeatureStatus::Supported,
                supported_capture_methods: supported_capture_methods.clone(),
                specific_features: None,
            },
        );

        worldpayxml_supported_payment_methods.add(
            common_enums::PaymentMethod::Wallet,
            common_enums::PaymentMethodType::ApplePay,
            PaymentMethodDetails {
                mandates: common_enums::FeatureStatus::Supported,
                refunds: common_enums::FeatureStatus::Supported,
                supported_capture_methods: supported_capture_methods.clone(),
                specific_features: None,
            },
        );
        worldpayxml_supported_payment_methods
    });

static WORLDPAYXML_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
    display_name: "Worldpay XML",
    description: "Worldpay is a payment gateway and PSP enabling secure online transactions",
    connector_type: common_enums::HyperswitchConnectorCategory::PaymentGateway,
    integration_status: common_enums::ConnectorIntegrationStatus::Sandbox,
};

static WORLDPAYXML_SUPPORTED_WEBHOOK_FLOWS: &[common_enums::EventClass] = &[
    common_enums::EventClass::Payments,
    common_enums::EventClass::Refunds,
    #[cfg(feature = "payouts")]
    common_enums::EventClass::Payouts,
];

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

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

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

    fn is_pre_authentication_flow_required(&self, current_flow: api::CurrentFlowInfo) -> bool {
        match current_flow {
            api::CurrentFlowInfo::Authorize {
                request_data,
                auth_type,
            } => {
                // Googlepay would require 3ds if cryptogram is not present which indicates it is Fpan
                auth_type == common_enums::AuthenticationType::ThreeDs
                    && match request_data.payment_method_data {
                        PaymentMethodData::Card(_) => true,
                        PaymentMethodData::Wallet(
                            hyperswitch_domain_models::payment_method_data::WalletData::GooglePay(
                                ref google_pay_data,
                            ),
                        ) => {
                            if let GpayTokenizationData::Decrypted(ref token) =
                                google_pay_data.tokenization_data
                            {
                                !(token.cryptogram.is_some() && token.eci_indicator.is_some())
                            } else {
                                false
                            }
                        }
                        _ => false,
                    }
            }
            // No alternate flow for complete authorize
            api::CurrentFlowInfo::CompleteAuthorize { .. } => false,
            api::CurrentFlowInfo::SetupMandate { .. } => false,
            api::CurrentFlowInfo::Psync { .. } => false,
            api::CurrentFlowInfo::UpdatePostConfirm { .. } => false,
            api::CurrentFlowInfo::ConnectorWebhookRegister { .. } => false,
        }
    }

    fn should_trigger_handle_response_without_body(&self) -> bool {
        true
    }

    fn generate_connector_customer_id(
        &self,
        customer_id: &Option<common_utils::id_type::CustomerId>,
        _merchant_id: &common_utils::id_type::MerchantId,
    ) -> Option<String> {
        customer_id
            .as_ref()
            .map(|cid| cid.get_string_repr().to_string())
    }
}
