package com.banesco.module.payment_order.infrastructure.client;

import com.banesco.common.application.helper.SerializationHelper;
import com.banesco.common.application.usecase.HttpClientUseCase;
import com.banesco.common.domain.exception.HttpStatusCodeException;
import com.banesco.common.domain.exception.ApiPrivateException;
import com.banesco.common.domain.model.*;
import com.banesco.common.infrastructure.config.RestClientConfig;
import com.banesco.module.payment_order.application.usecase.PaymentOrderUseCase;
import com.banesco.module.payment_order.domain.dto.request.PaymentOrderRequest;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

@Slf4j
@ApplicationScoped
public class PaymentOrderClient implements PaymentOrderUseCase {
    private final SerializationHelper serializationHelper;
    private final HttpClientUseCase httpClientUseCase;
    private final PaymentOrderConfig paymentOrderConfig;

    private static final String EMPTY_MESSAGE = "EMPTY_MESSAGE";

    @Inject
    public PaymentOrderClient(
        SerializationHelper serializationHelper,
        HttpClientUseCase httpClientUseCase,
        RestClientConfig restClientConfig
    ) {
        this.serializationHelper = serializationHelper;
        this.httpClientUseCase = httpClientUseCase;
        this.paymentOrderConfig = restClientConfig.getPaymentOrderConfig();
    }

    @Override
    public <T> List<T> execute(
        PaymentOrderRequest params,
        Class<T> responseType
    ) {
        String fintechId = params.getFintechId();
        String signatureIdentifier = getSignatureIdentifier(params);
        HttpRequest request = HttpRequest.forApiPrivateResponseList(
                paymentOrderConfig.getUrl(),
                paymentOrderConfig.getStatusSuccess(),
                HttpRequest.HttpMethod.GET,
                responseType
            )
            .withPathParams(Map.of("signatureIdentifier", signatureIdentifier))
            .withHeaders(Map.of("fintechId", fintechId))
            .withTimeout(
                paymentOrderConfig.getTimeout().getConnect(),
                paymentOrderConfig.getTimeout().getResponse()
            );

        try {
            ApiPrivateResponse<Either<List<T>, ApiPrivateError>> response =
                httpClientUseCase.executeApiPrivateResponseList(request);
            Either<List<T>, ApiPrivateError> detail = response.getDetalle();

            if(detail == null) {
                log.error(
                    "API retorno exitoso pero con detalle vacio. Codigo: {}, Mensaje: {}",
                    response.getEstatus(),
                    response.getMensaje()
                );

                throw ApiPrivateException.builder()
                    .statusCode("PIBE-00")
                    .message(EMPTY_MESSAGE)
                    .build();
            }

            if (detail.isLeft()) {
                if(detail.getLeft() == null) {
                    throw ApiPrivateException.builder()
                        .statusCode("PIBE-00")
                        .message(EMPTY_MESSAGE)
                        .build();
                }
                
                return detail.getLeft();
            }

            ApiPrivateError error = detail.getRight();

            log.error(
                "API privada retorno error. Codigo: {}, Mensaje: {}, Error Interno: {} -> {}",
                response.getEstatus(),
                response.getMensaje(),
                error.getCodError(),
                error.getMensajeError()
            );

            throw ApiPrivateException.builder()
                .statusCode("PIBE-01")
                .message((error.getCodError() != null)
                    ? error.getCodError() + ":" + error.getMensajeError()
                    : EMPTY_MESSAGE
                )
                .build();
        } catch (ApiPrivateException e) {
            throw e;
        } catch (HttpStatusCodeException e) {
            log.error(
                "Error HTTP consultando cliente {}: {} - {}",
                signatureIdentifier,
                e.getStatusCode(),
                e.getMessage()
            );
            throw e;
        } catch (Exception e) {
            log.error("Error cliente {}: {}", signatureIdentifier, e.getMessage());
            throw HttpStatusCodeException.serviceUnavailable("503");
        }
    }

    private String getSignatureIdentifier(PaymentOrderRequest params) {
        Map<String, Object> paymentOrderRequest = serializationHelper.toMap(params);
        Map<String, Object> operation = serializationHelper.toMap(params.getOperation());
        String signature = serializationHelper.generateSignature(
            params.getOperation(), params.getChannelId()
        );

        paymentOrderRequest.put("signature", signature);
        paymentOrderRequest.put("operation", operation);

        paymentOrderRequest.remove("fintechId");

        String signatureIdentifier = serializationHelper.encodeBase64(paymentOrderRequest);

        log.info("3. Firma generada: {}", signature);
        log.info("4. Parametros de la solicitud: {}", paymentOrderRequest);
        log.info("5. Solicitud final: {} -> {}", paymentOrderRequest, signatureIdentifier);

        return signatureIdentifier;
    }
}