pub mod transformers;

use std::fmt::Debug;

use common_enums::{CurrencyUnit, PaymentMethod, PaymentMethodType};

use common_utils::{
    errors::CustomResult, events, ext_traits::ByteSliceExt, request::Method, types::StringMajorUnit,
};
use domain_types::{
    connector_flow::{Authorize, Capture, PSync, PaymentMethodToken, RSync, Refund, Void},
    connector_types::{
        PaymentFlowData, PaymentMethodTokenResponse, PaymentMethodTokenizationData,
        PaymentVoidData, PaymentsAuthorizeData, PaymentsCaptureData, PaymentsResponseData,
        PaymentsSyncData, RefundFlowData, RefundSyncData, RefundsData, RefundsResponseData,
    },
    payment_method_data::PaymentMethodDataTypes,
    router_data::{ConnectorSpecificConfig, ErrorResponse},
    router_data_v2::RouterDataV2,
    router_response_types::Response,
    types::Connectors,
};
use error_stack::ResultExt;
use hyperswitch_masking::{ExposeInterface, Maskable};
use interfaces::{
    api::ConnectorCommon, connector_integration_v2::ConnectorIntegrationV2, connector_types,
    decode::BodyDecoding, verification::SourceVerification,
};
use serde::Serialize;
use transformers::{
    self as hipay, HipayAuthorizeResponse, HipayCaptureRequest, HipayCaptureResponse,
    HipayPSyncResponse, HipayPaymentsRequest, HipayRSyncResponse, HipayRefundRequest,
    HipayRefundResponse, HipayTokenRequest, HipayTokenResponse, HipayVoidRequest,
    HipayVoidResponse,
};

use super::macros;
use crate::{types::ResponseRouterData, with_error_response_body};
use domain_types::errors::{ConnectorError, IntegrationError};

pub(crate) mod headers {
    pub(crate) const CONTENT_TYPE: &str = "Content-Type";
    pub(crate) const AUTHORIZATION: &str = "Authorization";
    pub(crate) const ACCEPT: &str = "Accept";
}

pub(crate) mod constants {
    pub(crate) const JSON_CONTENT_TYPE: &str = "application/json";
}

// Struct definition and helper functions will be generated by create_all_prerequisites! macro below

impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
    connector_types::ConnectorServiceTrait<T> for Hipay<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
    connector_types::PaymentAuthorizeV2<T> for Hipay<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
    connector_types::PaymentSyncV2 for Hipay<T>
{
}

impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
    connector_types::PaymentVoidV2 for Hipay<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
    connector_types::RefundSyncV2 for Hipay<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
    connector_types::RefundV2 for Hipay<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
    connector_types::PaymentCapture for Hipay<T>
{
}
macros::macro_connector_payout_implementation!(
    connector: Hipay,
    generic_type: T,
    [PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize]
);
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
    connector_types::IncomingWebhook for Hipay<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
    connector_types::VerifyRedirectResponse for Hipay<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize> SourceVerification
    for Hipay<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize> BodyDecoding
    for Hipay<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
    connector_types::ValidationTrait for Hipay<T>
{
    fn should_do_payment_method_token(
        &self,
        _payment_method: PaymentMethod,
        _payment_method_type: Option<PaymentMethodType>,
    ) -> bool {
        true
    }
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
    connector_types::PaymentTokenV2<T> for Hipay<T>
{
}

// Authentication trait implementations

// Create connector struct with all flow prerequisites
macros::create_all_prerequisites!(
    connector_name: Hipay,
    generic_type: T,
    api: [
        (
            flow: PaymentMethodToken,
            request_body: HipayTokenRequest<T>,
            response_body: HipayTokenResponse,
            router_data: RouterDataV2<PaymentMethodToken, PaymentFlowData, PaymentMethodTokenizationData<T>, PaymentMethodTokenResponse>,
        ),
        (
            flow: Authorize,
            request_body: HipayPaymentsRequest,
            response_body: HipayAuthorizeResponse,
            router_data: RouterDataV2<Authorize, PaymentFlowData, PaymentsAuthorizeData<T>, PaymentsResponseData>,
        ),
        (
            flow: PSync,
            response_body: HipayPSyncResponse,
            router_data: RouterDataV2<PSync, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>,
        ),
        (
            flow: Capture,
            request_body: HipayCaptureRequest,
            response_body: HipayCaptureResponse,
            router_data: RouterDataV2<Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>,
        ),
        (
            flow: Void,
            request_body: HipayVoidRequest,
            response_body: HipayVoidResponse,
            router_data: RouterDataV2<Void, PaymentFlowData, PaymentVoidData, PaymentsResponseData>,
        ),
        (
            flow: Refund,
            request_body: HipayRefundRequest,
            response_body: HipayRefundResponse,
            router_data: RouterDataV2<Refund, RefundFlowData, RefundsData, RefundsResponseData>,
        )
    ],
    amount_converters: [
        amount_converter: StringMajorUnit
    ],
    member_functions: {
        pub fn get_tokenization_base_url<F, Req, Res>(
            &self,
            req: &RouterDataV2<F, PaymentFlowData, Req, Res>,
        ) -> CustomResult<String, IntegrationError> {
            // Use secondary_base_url from config for tokenization endpoint
            req.resource_common_data
                .connectors
                .hipay
                .secondary_base_url
                .as_ref()
                .cloned()
                .ok_or(error_stack::Report::new(IntegrationError::InvalidConnectorConfig {
                    config: "secondary_base_url",
                    context: Default::default()
}))
        }

        pub fn get_sync_base_url<F, Req, Res>(
            &self,
            req: &RouterDataV2<F, PaymentFlowData, Req, Res>,
        ) -> CustomResult<String, IntegrationError> {
            // Use third_base_url from config for sync operations (PSync)
            req.resource_common_data
                .connectors
                .hipay
                .third_base_url
                .as_ref()
                .cloned()
                .ok_or(error_stack::Report::new(IntegrationError::InvalidConnectorConfig {
                    config: "third_base_url",
                    context: Default::default()
}))
        }

        pub fn get_refund_sync_base_url<Req, Res>(
            &self,
            req: &RouterDataV2<RSync, RefundFlowData, Req, Res>,
        ) -> CustomResult<String, IntegrationError> {
            // Use third_base_url from config for refund sync operations
            req.resource_common_data
                .connectors
                .hipay
                .third_base_url
                .as_ref()
                .cloned()
                .ok_or(error_stack::Report::new(IntegrationError::InvalidConnectorConfig {
                    config: "third_base_url",
                    context: Default::default()
}))
        }

        pub fn build_headers<F, FCD, Req, Res>(
            &self,
            req: &RouterDataV2<F, FCD, Req, Res>,
        ) -> CustomResult<Vec<(String, Maskable<String>)>, IntegrationError>
        where
            Self: ConnectorIntegrationV2<F, FCD, Req, Res>,
        {
            let mut header = vec![
                (
                    headers::CONTENT_TYPE.to_string(),
                    self.common_get_content_type().to_string().into(),
                ),
                (
                    headers::ACCEPT.to_string(),
                    constants::JSON_CONTENT_TYPE.to_string().into(),
                ),
            ];
            let mut auth_header = self.get_auth_header(&req.connector_config)?;
            header.append(&mut auth_header);
            Ok(header)
        }

        pub fn connector_base_url_payments<'a, F, Req, Res>(
            &self,
            req: &'a RouterDataV2<F, PaymentFlowData, Req, Res>,
        ) -> &'a str {
            &req.resource_common_data.connectors.hipay.base_url
        }

        pub fn connector_base_url_refunds<'a, F, Req, Res>(
            &self,
            req: &'a RouterDataV2<F, RefundFlowData, Req, Res>,
        ) -> &'a str {
            &req.resource_common_data.connectors.hipay.base_url
        }
    }
);

impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize> ConnectorCommon
    for Hipay<T>
{
    fn id(&self) -> &'static str {
        "hipay"
    }

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

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

    fn get_auth_header(
        &self,
        auth_type: &ConnectorSpecificConfig,
    ) -> CustomResult<Vec<(String, Maskable<String>)>, IntegrationError> {
        let auth = hipay::HipayAuthType::try_from(auth_type).change_context(
            IntegrationError::FailedToObtainAuthType {
                context: Default::default(),
            },
        )?;

        // Use HTTP Basic Auth for HiPay
        use base64::Engine;
        let credentials = format!("{}:{}", auth.api_key.expose(), auth.api_secret.expose());
        let base64_credentials = base64::engine::general_purpose::STANDARD.encode(credentials);
        let auth_value = format!("Basic {base64_credentials}");

        Ok(vec![(
            headers::AUTHORIZATION.to_string(),
            auth_value.into(),
        )])
    }

    fn build_error_response(
        &self,
        res: Response,
        event_builder: Option<&mut events::Event>,
        _connector_config: &ConnectorSpecificConfig,
    ) -> CustomResult<ErrorResponse, ConnectorError> {
        let error_response: hipay::HipayErrorResponse = res
            .response
            .parse_struct("HipayErrorResponse")
            .unwrap_or_else(|_| {
                let raw_response = String::from_utf8_lossy(&res.response);
                let message = if raw_response.trim().is_empty() {
                    "Unknown error from HiPay".to_string()
                } else if raw_response.len() > 200 {
                    format!("{}...", &raw_response[..200])
                } else {
                    raw_response.to_string()
                };

                hipay::HipayErrorResponse {
                    code: res.status_code.to_string(),
                    message,
                }
            });

        with_error_response_body!(event_builder, error_response);

        Ok(ErrorResponse {
            status_code: res.status_code,
            code: error_response.code,
            message: error_response.message.clone(),
            reason: Some(error_response.message),
            attempt_status: None,
            connector_transaction_id: None,
            network_decline_code: None,
            network_advice_code: None,
            network_error_message: None,
        })
    }
}

// ========================================================================================
// MACRO-BASED FLOW IMPLEMENTATIONS
// ========================================================================================

// PaymentMethodToken flow - FormData (multipart/form-data), uses secondary_base_url
macros::macro_connector_implementation!(
    connector_default_implementations: [get_error_response_v2],
    connector: Hipay,
    curl_request: FormData(HipayTokenRequest<T>),
    curl_response: HipayTokenResponse,
    flow_name: PaymentMethodToken,
    resource_common_data: PaymentFlowData,
    flow_request: PaymentMethodTokenizationData<T>,
    flow_response: PaymentMethodTokenResponse,
    http_method: Post,
    generic_type: T,
    [PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize],
    other_functions: {
        fn get_headers(
            &self,
            req: &RouterDataV2<PaymentMethodToken, PaymentFlowData, PaymentMethodTokenizationData<T>, PaymentMethodTokenResponse>,
        ) -> CustomResult<Vec<(String, Maskable<String>)>, IntegrationError> {
            // Do NOT set Content-Type header manually for FormData - reqwest sets it with boundary
            let mut header = vec![(
                headers::ACCEPT.to_string(),
                constants::JSON_CONTENT_TYPE.to_string().into(),
            )];
            let mut auth_header = self.get_auth_header(&req.connector_config)?;
            header.append(&mut auth_header);
            Ok(header)
        }

        fn get_url(
            &self,
            req: &RouterDataV2<PaymentMethodToken, PaymentFlowData, PaymentMethodTokenizationData<T>, PaymentMethodTokenResponse>,
        ) -> CustomResult<String, IntegrationError> {
            let base_url = self.get_tokenization_base_url(req)?;
            Ok(format!("{}/create", base_url.trim_end_matches('/')))
        }
    }
);

// Authorize flow - FormData (multipart/form-data), uses base_url
macros::macro_connector_implementation!(
    connector_default_implementations: [get_error_response_v2],
    connector: Hipay,
    curl_request: FormData(HipayPaymentsRequest),
    curl_response: HipayAuthorizeResponse,
    flow_name: Authorize,
    resource_common_data: PaymentFlowData,
    flow_request: PaymentsAuthorizeData<T>,
    flow_response: PaymentsResponseData,
    http_method: Post,
    generic_type: T,
    [PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize],
    other_functions: {
        fn get_headers(
            &self,
            req: &RouterDataV2<Authorize, PaymentFlowData, PaymentsAuthorizeData<T>, PaymentsResponseData>,
        ) -> CustomResult<Vec<(String, Maskable<String>)>, IntegrationError> {
            // Do NOT set Content-Type header manually for FormData - reqwest sets it with boundary
            let mut header = vec![(
                headers::ACCEPT.to_string(),
                constants::JSON_CONTENT_TYPE.to_string().into(),
            )];
            let mut auth_header = self.get_auth_header(&req.connector_config)?;
            header.append(&mut auth_header);
            Ok(header)
        }

        fn get_url(
            &self,
            req: &RouterDataV2<Authorize, PaymentFlowData, PaymentsAuthorizeData<T>, PaymentsResponseData>,
        ) -> CustomResult<String, IntegrationError> {
            Ok(format!(
                "{}/v1/order",
                self.connector_base_url_payments(req).trim_end_matches('/')
            ))
        }
    }
);

// PSync flow - GET, no request body, JSON response, uses third_base_url
macros::macro_connector_implementation!(
    connector_default_implementations: [get_error_response_v2],
    connector: Hipay,
    curl_response: HipayPSyncResponse,
    flow_name: PSync,
    resource_common_data: PaymentFlowData,
    flow_request: PaymentsSyncData,
    flow_response: PaymentsResponseData,
    http_method: Get,
    generic_type: T,
    [PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize],
    other_functions: {
        fn get_headers(
            &self,
            req: &RouterDataV2<PSync, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>,
        ) -> CustomResult<Vec<(String, Maskable<String>)>, IntegrationError> {
            self.build_headers(req)
        }

        fn get_url(
            &self,
            req: &RouterDataV2<PSync, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>,
        ) -> CustomResult<String, IntegrationError> {
            let transaction_reference = req
                .request
                .connector_transaction_id
                .get_connector_transaction_id()
                .change_context(IntegrationError::MissingConnectorTransactionID { context: Default::default() })?;

            let base_url = self.get_sync_base_url(req)?;
            Ok(format!(
                "{}/v3/transaction/{}",
                base_url.trim_end_matches('/'),
                transaction_reference
            ))
        }
    }
);

// Capture flow - FormData (multipart/form-data), uses base_url
macros::macro_connector_implementation!(
    connector_default_implementations: [get_error_response_v2],
    connector: Hipay,
    curl_request: FormData(HipayCaptureRequest),
    curl_response: HipayCaptureResponse,
    flow_name: Capture,
    resource_common_data: PaymentFlowData,
    flow_request: PaymentsCaptureData,
    flow_response: PaymentsResponseData,
    http_method: Post,
    generic_type: T,
    [PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize],
    other_functions: {
        fn get_headers(
            &self,
            req: &RouterDataV2<Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>,
        ) -> CustomResult<Vec<(String, Maskable<String>)>, IntegrationError> {
            // Do NOT set Content-Type header manually for FormData - reqwest sets it with boundary
            let mut header = vec![(
                headers::ACCEPT.to_string(),
                constants::JSON_CONTENT_TYPE.to_string().into(),
            )];
            let mut auth_header = self.get_auth_header(&req.connector_config)?;
            header.append(&mut auth_header);
            Ok(header)
        }

        fn get_url(
            &self,
            req: &RouterDataV2<Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>,
        ) -> CustomResult<String, IntegrationError> {
            let transaction_reference = req
                .request
                .connector_transaction_id
                .get_connector_transaction_id()
                .change_context(IntegrationError::MissingConnectorTransactionID { context: Default::default() })?;

            Ok(format!(
                "{}/v1/maintenance/transaction/{}",
                self.connector_base_url_payments(req).trim_end_matches('/'),
                transaction_reference
            ))
        }
    }
);

// Void flow - FormData (multipart/form-data), uses base_url
macros::macro_connector_implementation!(
    connector_default_implementations: [get_error_response_v2],
    connector: Hipay,
    curl_request: FormData(HipayVoidRequest),
    curl_response: HipayVoidResponse,
    flow_name: Void,
    resource_common_data: PaymentFlowData,
    flow_request: PaymentVoidData,
    flow_response: PaymentsResponseData,
    http_method: Post,
    generic_type: T,
    [PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize],
    other_functions: {
        fn get_headers(
            &self,
            req: &RouterDataV2<Void, PaymentFlowData, PaymentVoidData, PaymentsResponseData>,
        ) -> CustomResult<Vec<(String, Maskable<String>)>, IntegrationError> {
            // Do NOT set Content-Type header manually for FormData - reqwest sets it with boundary
            let mut header = vec![(
                headers::ACCEPT.to_string(),
                constants::JSON_CONTENT_TYPE.to_string().into(),
            )];
            let mut auth_header = self.get_auth_header(&req.connector_config)?;
            header.append(&mut auth_header);
            Ok(header)
        }

        fn get_url(
            &self,
            req: &RouterDataV2<Void, PaymentFlowData, PaymentVoidData, PaymentsResponseData>,
        ) -> CustomResult<String, IntegrationError> {
            let transaction_reference = &req.request.connector_transaction_id;

            Ok(format!(
                "{}/v1/maintenance/transaction/{}",
                self.connector_base_url_payments(req).trim_end_matches('/'),
                transaction_reference
            ))
        }
    }
);

// Refund flow - FormData (multipart/form-data), uses base_url
macros::macro_connector_implementation!(
    connector_default_implementations: [get_error_response_v2],
    connector: Hipay,
    curl_request: FormData(HipayRefundRequest),
    curl_response: HipayRefundResponse,
    flow_name: Refund,
    resource_common_data: RefundFlowData,
    flow_request: RefundsData,
    flow_response: RefundsResponseData,
    http_method: Post,
    generic_type: T,
    [PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize],
    other_functions: {
        fn get_headers(
            &self,
            req: &RouterDataV2<Refund, RefundFlowData, RefundsData, RefundsResponseData>,
        ) -> CustomResult<Vec<(String, Maskable<String>)>, IntegrationError> {
            // Do NOT set Content-Type header manually for FormData - reqwest sets it with boundary
            let mut header = vec![(
                headers::ACCEPT.to_string(),
                constants::JSON_CONTENT_TYPE.to_string().into(),
            )];
            let mut auth_header = self.get_auth_header(&req.connector_config)?;
            header.append(&mut auth_header);
            Ok(header)
        }

        fn get_url(
            &self,
            req: &RouterDataV2<Refund, RefundFlowData, RefundsData, RefundsResponseData>,
        ) -> CustomResult<String, IntegrationError> {
            let transaction_reference = req.request.connector_transaction_id.clone();

            Ok(format!(
                "{}/v1/maintenance/transaction/{}",
                self.connector_base_url_refunds(req).trim_end_matches('/'),
                transaction_reference
            ))
        }
    }
);

// RSync flow - Manual implementation with custom handle_response_v2
// Uses JSON deserialization from v3 API (same as PSync)
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
    ConnectorIntegrationV2<RSync, RefundFlowData, RefundSyncData, RefundsResponseData>
    for Hipay<T>
{
    fn get_http_method(&self) -> Method {
        Method::Get
    }

    fn get_headers(
        &self,
        req: &RouterDataV2<RSync, RefundFlowData, RefundSyncData, RefundsResponseData>,
    ) -> CustomResult<Vec<(String, Maskable<String>)>, IntegrationError> {
        let mut header = vec![(
            headers::CONTENT_TYPE.to_string(),
            self.common_get_content_type().to_string().into(),
        )];
        let mut auth_header = self.get_auth_header(&req.connector_config)?;
        header.append(&mut auth_header);
        Ok(header)
    }

    fn get_url(
        &self,
        req: &RouterDataV2<RSync, RefundFlowData, RefundSyncData, RefundsResponseData>,
    ) -> CustomResult<String, IntegrationError> {
        let transaction_reference = req.request.connector_refund_id.clone();

        let base_url = self.get_refund_sync_base_url(req)?;
        Ok(format!(
            "{}/v3/transaction/{}",
            base_url.trim_end_matches('/'),
            transaction_reference
        ))
    }

    fn handle_response_v2(
        &self,
        data: &RouterDataV2<RSync, RefundFlowData, RefundSyncData, RefundsResponseData>,
        event_builder: Option<&mut events::Event>,
        res: Response,
    ) -> CustomResult<
        RouterDataV2<RSync, RefundFlowData, RefundSyncData, RefundsResponseData>,
        ConnectorError,
    > {
        // HiPay RSync returns JSON from v3 API (same as PSync)
        let response: HipayRSyncResponse = res
            .response
            .parse_struct("HipayRSyncResponse")
            .change_context(crate::utils::response_handling_fail_for_connector(
                res.status_code,
                "hipay",
            ))?;

        if let Some(event) = event_builder {
            event.set_connector_response(&response);
        }

        RouterDataV2::try_from(ResponseRouterData {
            response,
            router_data: data.clone(),
            http_code: res.status_code,
        })
        .change_context(crate::utils::response_handling_fail_for_connector(
            res.status_code,
            "hipay",
        ))
    }

    fn get_error_response_v2(
        &self,
        res: Response,
        event_builder: Option<&mut events::Event>,
        _connector_config: &ConnectorSpecificConfig,
    ) -> CustomResult<ErrorResponse, ConnectorError> {
        self.build_error_response(res, event_builder, _connector_config)
    }

    fn get_5xx_error_response(
        &self,
        res: Response,
        event_builder: Option<&mut events::Event>,
        _connector_config: &ConnectorSpecificConfig,
    ) -> CustomResult<ErrorResponse, ConnectorError> {
        self.build_error_response(res, event_builder, _connector_config)
    }
}

macros::macro_connector_flow_status_impls!(
    connector: Hipay,
    generic_type: T,
    [PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize],
    not_implemented: [
        SetupMandate,
        RepeatPayment,
        CreateOrder,
        Accept,
    ],
    not_supported: [
        VoidPostRefund,
        IncrementalAuthorization,
        PreAuthenticate,
        VoidPC,
        ServerSessionAuthenticationToken,
        ClientAuthenticationToken,
        MandateRevoke,
        DefendDispute,
        SubmitEvidence,
        ServerAuthenticationToken,
        Authenticate,
        PostAuthenticate,
        CreateConnectorCustomer,
        GetConnectorCustomer,
    ],
);
