pub mod transformers;
use std::sync::LazyLock;

use api_models::webhooks::IncomingWebhookEvent;
use base64::Engine;
use common_enums::{enums, CallConnectorAction, CaptureMethod, PaymentAction, PaymentMethodType};
use common_utils::{
    consts::BASE64_ENGINE,
    crypto,
    errors::CustomResult,
    ext_traits::{ByteSliceExt, BytesExt},
    request::{Method, Request, RequestBuilder, RequestContent},
    types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},
};
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, PSync, PaymentMethodToken, PreProcessing, Session,
            SettlementSplitCreate, SetupMandate, Void,
        },
        refunds::{Execute, RSync},
    },
    router_request_types::{
        AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
        PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData, PaymentsSessionData,
        PaymentsSyncData, RefundsData, SettlementSplitRequestData, SetupMandateRequestData,
        SplitRefundsRequest,
    },
    router_response_types::{
        ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
        SupportedPaymentMethods, SupportedPaymentMethodsExt,
    },
    types::{
        PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
        PaymentsPreProcessingRouterData, PaymentsSettlementSplitCreateRouterData,
        PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
    },
};
use hyperswitch_interfaces::{
    api::{
        self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse,
        ConnectorSpecifications, ConnectorValidation,
    },
    configs::Connectors,
    errors,
    events::connector_api_logs::ConnectorEvent,
    types::{self, PaymentsAuthorizeType, PaymentsCaptureType, PaymentsSyncType, Response},
    webhooks,
};
use hyperswitch_masking::{Mask, PeekInterface};
use image::EncodableLayout;
use transformers::{self as xendit, XenditEventType, XenditWebhookEvent};

use crate::{
    constants::headers,
    types::ResponseRouterData,
    utils as connector_utils,
    utils::{self, RefundsRequestData},
};

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

impl Xendit {
    pub fn new() -> &'static Self {
        &Self {
            amount_converter: &FloatMajorUnitForConnector,
        }
    }
}
impl api::Payment for Xendit {}
impl api::PaymentsSettlementSplitCreate for Xendit {}
impl api::PaymentsPreProcessing for Xendit {}
impl api::PaymentSession for Xendit {}
impl api::ConnectorAccessToken for Xendit {}
impl api::MandateSetup for Xendit {}
impl api::PaymentAuthorize for Xendit {}
impl api::PaymentSync for Xendit {}
impl api::PaymentCapture for Xendit {}
impl api::PaymentVoid for Xendit {}
impl api::Refund for Xendit {}
impl api::RefundExecute for Xendit {}
impl api::RefundSync for Xendit {}
impl api::PaymentToken for Xendit {}

impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
    for Xendit
{
}

impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Xendit
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.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 Xendit {
    fn id(&self) -> &'static str {
        "xendit"
    }

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

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

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

    fn get_auth_header(
        &self,
        auth_type: &ConnectorAuthType,
    ) -> CustomResult<Vec<(String, hyperswitch_masking::Maskable<String>)>, errors::ConnectorError>
    {
        let auth = xendit::XenditAuthType::try_from(auth_type)
            .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
        let encoded_api_key = BASE64_ENGINE.encode(format!("{}:", auth.api_key.peek()));

        Ok(vec![(
            headers::AUTHORIZATION.to_string(),
            format!("Basic {encoded_api_key}").into_masked(),
        )])
    }
    fn build_error_response(
        &self,
        res: Response,
        event_builder: Option<&mut ConnectorEvent>,
    ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
        let error_response: xendit::XenditErrorResponse = res
            .response
            .parse_struct("ErrorResponse")
            .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;

        event_builder.map(|i| i.set_error_response_body(&error_response));
        router_env::logger::info!(connector_response=?error_response);
        Ok(ErrorResponse {
            code: error_response.error_code.clone(),
            message: error_response.message.clone(),
            reason: Some(error_response.message.clone()),
            status_code: res.status_code,
            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,
        })
    }
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Xendit {
    fn build_request(
        &self,
        _req: &PaymentsCancelRouterData,
        _connectors: &Connectors,
    ) -> CustomResult<Option<Request>, errors::ConnectorError> {
        Err(errors::ConnectorError::NotSupported {
            message: "Cancel/Void flow".to_string(),
            connector: "Xendit",
        }
        .into())
    }
}

impl ConnectorValidation for Xendit {}

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

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

impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Xendit {}

impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Xendit {
    fn get_headers(
        &self,
        req: &PaymentsAuthorizeRouterData,
        connectors: &Connectors,
    ) -> CustomResult<Vec<(String, hyperswitch_masking::Maskable<String>)>, errors::ConnectorError>
    {
        let mut headers = self.build_headers(req, connectors)?;

        match &req.request.split_payments {
            Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment(
                common_types::payments::XenditSplitRequest::MultipleSplits(_),
            )) => {
                if let Ok(PaymentsResponseData::TransactionResponse {
                    authentication_data: None,
                    charges:
                        Some(common_types::payments::ConnectorChargeResponseData::XenditSplitPayment(
                            common_types::payments::XenditChargeResponseData::MultipleSplits(
                                xendit_response,
                            ),
                        )),
                    ..
                }) = req.response.as_ref()
                {
                    headers.push((
                        xendit::auth_headers::WITH_SPLIT_RULE.to_string(),
                        xendit_response.split_rule_id.clone().into(),
                    ));
                    if let Some(for_user_id) = &xendit_response.for_user_id {
                        headers.push((
                            xendit::auth_headers::FOR_USER_ID.to_string(),
                            for_user_id.clone().into(),
                        ))
                    };
                };
            }
            Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment(
                common_types::payments::XenditSplitRequest::SingleSplit(single_split_data),
            )) => {
                headers.push((
                    xendit::auth_headers::FOR_USER_ID.to_string(),
                    single_split_data.for_user_id.clone().into(),
                ));
            }
            _ => (),
        };

        Ok(headers)
    }

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

    fn get_url(
        &self,
        req: &PaymentsAuthorizeRouterData,
        connectors: &Connectors,
    ) -> CustomResult<String, errors::ConnectorError> {
        let base_url = self.base_url(connectors);
        match req.request.payment_method_type {
            Some(PaymentMethodType::Qris) => Ok(format!("{}/qr_codes", base_url)),
            _ => Ok(format!("{}/payment_requests", 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 = xendit::XenditRouterData::from((amount, req));
        let connector_req = xendit::XenditPaymentsRequest::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(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
                .attach_default_headers()
                .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
                .set_body(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: xendit::XenditPaymentResponse = res
            .response
            .parse_struct("XenditPaymentResponse")
            .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;

        let response_integrity_object = connector_utils::get_authorise_integrity_object(
            self.amount_converter,
            response.amount,
            response
                .currency
                .unwrap_or(data.request.currency)
                .to_string()
                .clone(),
        )?;

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

        let new_router_data = RouterData::try_from(ResponseRouterData {
            response,
            data: data.clone(),
            http_code: res.status_code,
        })
        .change_context(errors::ConnectorError::ResponseHandlingFailed);

        new_router_data.map(|mut router_data| {
            router_data.request.integrity_object = Some(response_integrity_object);
            router_data
        })
    }

    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<SettlementSplitCreate, SettlementSplitRequestData, PaymentsResponseData>
    for Xendit
{
    fn get_headers(
        &self,
        req: &PaymentsSettlementSplitCreateRouterData,
        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: &PaymentsSettlementSplitCreateRouterData,
        connectors: &Connectors,
    ) -> CustomResult<String, errors::ConnectorError> {
        Ok(format!("{}/split_rules", self.base_url(connectors)))
    }

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

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

    fn handle_response(
        &self,
        data: &PaymentsSettlementSplitCreateRouterData,
        event_builder: Option<&mut ConnectorEvent>,
        res: Response,
    ) -> CustomResult<PaymentsSettlementSplitCreateRouterData, errors::ConnectorError> {
        let response: xendit::XenditSplitResponse = res
            .response
            .parse_struct("XenditSplitResponse")
            .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<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>
    for Xendit
{
    fn get_headers(
        &self,
        req: &PaymentsPreProcessingRouterData,
        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: &PaymentsPreProcessingRouterData,
        connectors: &Connectors,
    ) -> CustomResult<String, errors::ConnectorError> {
        Ok(format!("{}/split_rules", self.base_url(connectors)))
    }

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

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

    fn handle_response(
        &self,
        data: &PaymentsPreProcessingRouterData,
        event_builder: Option<&mut ConnectorEvent>,
        res: Response,
    ) -> CustomResult<PaymentsPreProcessingRouterData, errors::ConnectorError> {
        let response: xendit::XenditSplitResponse = res
            .response
            .parse_struct("XenditSplitResponse")
            .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 Xendit {
    fn get_headers(
        &self,
        req: &PaymentsSyncRouterData,
        connectors: &Connectors,
    ) -> CustomResult<Vec<(String, hyperswitch_masking::Maskable<String>)>, errors::ConnectorError>
    {
        let mut headers = self.build_headers(req, connectors)?;

        match &req.request.split_payments {
            Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment(
                common_types::payments::XenditSplitRequest::MultipleSplits(xendit_request),
            )) => {
                if let Some(for_user_id) = &xendit_request.for_user_id {
                    headers.push((
                        xendit::auth_headers::FOR_USER_ID.to_string(),
                        for_user_id.clone().into(),
                    ))
                };
            }
            Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment(
                common_types::payments::XenditSplitRequest::SingleSplit(single_split_data),
            )) => {
                headers.push((
                    xendit::auth_headers::FOR_USER_ID.to_string(),
                    single_split_data.for_user_id.clone().into(),
                ));
            }
            _ => (),
        };

        Ok(headers)
    }

    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!(
            "{}/payment_requests/{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(&PaymentsSyncType::get_url(self, req, connectors)?)
                .attach_default_headers()
                .headers(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: xendit::XenditResponse = res
            .response
            .clone()
            .parse_struct("xendit XenditResponse")
            .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;

        let response_integrity_object = match response.clone() {
            xendit::XenditResponse::Payment(p) => connector_utils::get_sync_integrity_object(
                self.amount_converter,
                p.amount,
                p.currency
                    .unwrap_or(data.request.currency)
                    .to_string()
                    .clone(),
            ),
            xendit::XenditResponse::Webhook(webhook_response_data) => match webhook_response_data {
                XenditWebhookEvent::CommonEvent(event_data) => {
                    connector_utils::get_sync_integrity_object(
                        self.amount_converter,
                        event_data.data.amount,
                        event_data.data.currency.clone(),
                    )
                }
                XenditWebhookEvent::QrEvent(xendit_qris_webhook_response_data) => {
                    connector_utils::get_sync_integrity_object(
                        self.amount_converter,
                        xendit_qris_webhook_response_data.amount,
                        data.request.currency.to_string(),
                    )
                }
            },
        };

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

        let new_router_data = RouterData::try_from(ResponseRouterData {
            response,
            data: data.clone(),
            http_code: res.status_code,
        });
        new_router_data.and_then(|mut router_data| {
            let integrity_object = response_integrity_object?;
            router_data.request.integrity_object = Some(integrity_object);
            Ok(router_data)
        })
    }
}

impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Xendit {
    fn get_headers(
        &self,
        req: &PaymentsCaptureRouterData,
        connectors: &Connectors,
    ) -> CustomResult<Vec<(String, hyperswitch_masking::Maskable<String>)>, errors::ConnectorError>
    {
        let mut headers = self.build_headers(req, connectors)?;

        match &req.request.split_payments {
            Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment(
                common_types::payments::XenditSplitRequest::MultipleSplits(xendit_request),
            )) => {
                if let Some(for_user_id) = &xendit_request.for_user_id {
                    headers.push((
                        xendit::auth_headers::FOR_USER_ID.to_string(),
                        for_user_id.clone().into(),
                    ))
                };
            }
            Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment(
                common_types::payments::XenditSplitRequest::SingleSplit(single_split_data),
            )) => {
                headers.push((
                    xendit::auth_headers::FOR_USER_ID.to_string(),
                    single_split_data.for_user_id.clone().into(),
                ));
            }
            _ => (),
        };

        Ok(headers)
    }

    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!(
            "{}/payment_requests/{connector_payment_id}/captures",
            self.base_url(connectors),
        ))
    }

    fn get_request_body(
        &self,
        req: &PaymentsCaptureRouterData,
        _connectors: &Connectors,
    ) -> CustomResult<RequestContent, errors::ConnectorError> {
        let amount_to_capture = utils::convert_amount(
            self.amount_converter,
            req.request.minor_amount_to_capture,
            req.request.currency,
        )?;
        let authorized_amount = utils::convert_amount(
            self.amount_converter,
            req.request.minor_payment_amount,
            req.request.currency,
        )?;
        if amount_to_capture != authorized_amount {
            Err(report!(errors::ConnectorError::NotSupported {
                message: "Partial Capture".to_string(),
                connector: "Xendit"
            }))
        } else {
            let connector_router_data = xendit::XenditRouterData::from((amount_to_capture, req));
            let connector_req =
                xendit::XenditPaymentsCaptureRequest::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(&PaymentsCaptureType::get_url(self, req, connectors)?)
                .attach_default_headers()
                .headers(PaymentsCaptureType::get_headers(self, req, connectors)?)
                .set_body(self.get_request_body(req, connectors)?)
                .build(),
        ))
    }

    fn handle_response(
        &self,
        data: &PaymentsCaptureRouterData,
        event_builder: Option<&mut ConnectorEvent>,
        res: Response,
    ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
        let response: xendit::XenditCaptureResponse = res
            .response
            .parse_struct("Xendit PaymentsResponse")
            .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,
        })
        .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)
    }
}

impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Xendit {
    fn get_headers(
        &self,
        req: &RefundsRouterData<Execute>,
        connectors: &Connectors,
    ) -> CustomResult<Vec<(String, hyperswitch_masking::Maskable<String>)>, errors::ConnectorError>
    {
        let mut headers = self.build_headers(req, connectors)?;
        if let Some(SplitRefundsRequest::XenditSplitRefund(sub_merchant_data)) =
            &req.request.split_refunds
        {
            headers.push((
                xendit::auth_headers::FOR_USER_ID.to_string(),
                sub_merchant_data.for_user_id.clone().into(),
            ));
        };

        Ok(headers)
    }

    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 amount = utils::convert_amount(
            self.amount_converter,
            req.request.minor_refund_amount,
            req.request.currency,
        )?;
        let connector_router_data = xendit::XenditRouterData::from((amount, req));
        let connector_req = xendit::XenditRefundRequest::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: xendit::RefundResponse =
            res.response
                .parse_struct("xendit RefundResponse")
                .change_context(errors::ConnectorError::RequestEncodingFailed)?;

        let response_integrity_object = connector_utils::get_refund_integrity_object(
            self.amount_converter,
            response.amount,
            response.currency.to_string().clone(),
        )?;

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

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

        new_router_data
            .map(|mut router_data| {
                router_data.request.integrity_object = Some(response_integrity_object);
                router_data
            })
            .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)
    }
}

impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Xendit {
    fn get_headers(
        &self,
        req: &RefundSyncRouterData,
        connectors: &Connectors,
    ) -> CustomResult<Vec<(String, hyperswitch_masking::Maskable<String>)>, errors::ConnectorError>
    {
        let mut headers = self.build_headers(req, connectors)?;
        if let Some(SplitRefundsRequest::XenditSplitRefund(sub_merchant_data)) =
            &req.request.split_refunds
        {
            headers.push((
                xendit::auth_headers::FOR_USER_ID.to_string(),
                sub_merchant_data.for_user_id.clone().into(),
            ));
        };

        Ok(headers)
    }

    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 connector_refund_id = req.request.get_connector_refund_id()?;
        Ok(format!(
            "{}/refunds/{}",
            self.base_url(connectors),
            connector_refund_id
        ))
    }

    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)?)
                .build(),
        ))
    }

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

        let response_integrity_object = connector_utils::get_refund_integrity_object(
            self.amount_converter,
            response.amount,
            response.currency.to_string().clone(),
        )?;

        event_builder.map(|i| i.set_response_body(&response));
        router_env::logger::info!(connector_response=?response);
        let new_router_data = RouterData::try_from(ResponseRouterData {
            response,
            data: data.clone(),
            http_code: res.status_code,
        });

        new_router_data
            .map(|mut router_data| {
                router_data.request.integrity_object = Some(response_integrity_object);
                router_data
            })
            .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)
    }
}

#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Xendit {
    fn get_webhook_source_verification_signature(
        &self,
        request: &webhooks::IncomingWebhookRequestDetails<'_>,
        _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
    ) -> CustomResult<Vec<u8>, errors::ConnectorError> {
        let header_value = utils::get_header_key_value("X-CALLBACK-TOKEN", request.headers)?;
        Ok(header_value.into())
    }
    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: crypto::Encryptable<
            hyperswitch_masking::Secret<serde_json::Value>,
        >,
        connector_label: &str,
    ) -> CustomResult<bool, errors::ConnectorError> {
        let connector_webhook_secrets = self
            .get_webhook_source_verification_merchant_secret(
                merchant_id,
                connector_label,
                connector_webhook_details,
            )
            .await
            .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
        let signature = self
            .get_webhook_source_verification_signature(request, &connector_webhook_secrets)
            .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;

        let secret_key = connector_webhook_secrets.secret;
        Ok(secret_key.as_bytes() == (signature).as_bytes())
    }
    fn get_webhook_source_verification_message(
        &self,
        request: &webhooks::IncomingWebhookRequestDetails<'_>,
        _merchant_id: &common_utils::id_type::MerchantId,
        _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
    ) -> CustomResult<Vec<u8>, errors::ConnectorError> {
        Ok(request.body.to_vec())
    }
    fn get_webhook_object_reference_id(
        &self,
        request: &webhooks::IncomingWebhookRequestDetails<'_>,
    ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
        let details: XenditWebhookEvent = request
            .body
            .parse_struct("XenditWebhookEvent")
            .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
        match details {
            XenditWebhookEvent::CommonEvent(event_data) => match event_data.event {
                XenditEventType::PaymentSucceeded
                | XenditEventType::PaymentAwaitingCapture
                | XenditEventType::PaymentFailed
                | XenditEventType::CaptureSucceeded
                | XenditEventType::CaptureFailed => {
                    Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
                        api_models::payments::PaymentIdType::ConnectorTransactionId(
                            event_data
                                .data
                                .payment_request_id
                                .ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?,
                        ),
                    ))
                }
                XenditEventType::QrPayment => {
                    Err(errors::ConnectorError::WebhookReferenceIdNotFound.into())
                }
            },
            XenditWebhookEvent::QrEvent(xendit_qris_webhook_event_data) => {
                Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
                    api_models::payments::PaymentIdType::ConnectorTransactionId(
                        xendit_qris_webhook_event_data.qr_code.external_id,
                    ),
                ))
            }
        }
    }

    fn get_webhook_event_type(
        &self,
        request: &webhooks::IncomingWebhookRequestDetails<'_>,
        _context: Option<&webhooks::WebhookContext>,
    ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
        let body: XenditWebhookEvent = request
            .body
            .parse_struct("XenditWebhookEvent")
            .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
        match body {
            XenditWebhookEvent::CommonEvent(event_data) => match event_data.event {
                XenditEventType::PaymentSucceeded | XenditEventType::QrPayment => {
                    Ok(IncomingWebhookEvent::PaymentIntentSuccess)
                }
                XenditEventType::CaptureSucceeded => {
                    Ok(IncomingWebhookEvent::PaymentIntentCaptureSuccess)
                }
                XenditEventType::PaymentAwaitingCapture => {
                    Ok(IncomingWebhookEvent::PaymentIntentAuthorizationSuccess)
                }
                XenditEventType::PaymentFailed | XenditEventType::CaptureFailed => {
                    Ok(IncomingWebhookEvent::PaymentIntentFailure)
                }
            },
            // Xendit’s QR Code system currently only sends a webhook for a successful payment
            XenditWebhookEvent::QrEvent(_) => Ok(IncomingWebhookEvent::PaymentIntentSuccess),
        }
    }

    fn get_webhook_resource_object(
        &self,
        request: &webhooks::IncomingWebhookRequestDetails<'_>,
    ) -> CustomResult<Box<dyn hyperswitch_masking::ErasedMaskSerialize>, errors::ConnectorError>
    {
        let body: XenditWebhookEvent = request
            .body
            .parse_struct("XenditWebhookEvent")
            .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
        Ok(Box::new(body))
    }
}

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

    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 xendit_supported_payment_methods = SupportedPaymentMethods::new();

    xendit_supported_payment_methods.add(
        enums::PaymentMethod::Card,
        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::Supported,
                        no_three_ds: common_enums::FeatureStatus::Supported,
                        supported_card_networks: supported_card_network.clone(),
                    }
                }),
            ),
        },
    );

    xendit_supported_payment_methods.add(
        enums::PaymentMethod::Card,
        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::Supported,
                        no_three_ds: common_enums::FeatureStatus::Supported,
                        supported_card_networks: supported_card_network.clone(),
                    }
                }),
            ),
        },
    );

    xendit_supported_payment_methods.add(
        enums::PaymentMethod::RealTimePayment,
        PaymentMethodType::Qris,
        PaymentMethodDetails {
            mandates: enums::FeatureStatus::Supported,
            refunds: enums::FeatureStatus::Supported,
            supported_capture_methods: automatic_capture_supported.clone(),
            specific_features: None,
        },
    );

    xendit_supported_payment_methods
});

static XENDIT_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
    display_name: "Xendit",
    description: "Xendit is a financial technology company that provides payment solutions and simplifies the payment process for businesses in Indonesia, the Philippines and Southeast Asia, from SMEs and e-commerce startups to large enterprises.",
    connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
    integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};

static XENDIT_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 1] = [enums::EventClass::Payments];

impl ConnectorSpecifications for Xendit {
    fn is_settlement_split_call_required(&self, current_flow: api::CurrentFlowInfo) -> bool {
        match current_flow {
            api::CurrentFlowInfo::Authorize { request_data, .. } => {
                matches!(request_data.payment_method_data, PaymentMethodData::Card(_))
                    && matches!(
                        request_data.split_payments.as_ref(),
                        Some(
                            common_types::payments::SplitPaymentsRequest::XenditSplitPayment(
                                common_types::payments::XenditSplitRequest::MultipleSplits(_),
                            ),
                        )
                    )
            }
            api::CurrentFlowInfo::SetupMandate { .. }
            | api::CurrentFlowInfo::CompleteAuthorize { .. }
            | api::CurrentFlowInfo::Psync { .. }
            | api::CurrentFlowInfo::ConnectorWebhookRegister { .. }
            | api::CurrentFlowInfo::UpdatePostConfirm { .. } => false,
        }
    }
    fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
        Some(&XENDIT_CONNECTOR_INFO)
    }

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

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

impl ConnectorRedirectResponse for Xendit {
    fn get_flow_type(
        &self,
        _query_params: &str,
        _json_payload: Option<serde_json::Value>,
        action: PaymentAction,
    ) -> CustomResult<CallConnectorAction, errors::ConnectorError> {
        match action {
            PaymentAction::PSync
            | PaymentAction::PaymentAuthenticateCompleteAuthorize
            | PaymentAction::CompleteAuthorize => Ok(CallConnectorAction::Trigger),
        }
    }
}
