package com.banesco.module.payment_request.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_request.application.usecase.PaymentRequestUseCase;
import com.banesco.module.payment_request.domain.dto.request.PaymentRequestRequest;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

@Slf4j
@ApplicationScoped
public class PaymentRequestClient implements PaymentRequestUseCase {
    private final SerializationHelper serializationHelper;
    private final HttpClientUseCase httpClientUseCase;
    private final PaymentRequestConfig paymentStatusConfig;

    @Inject
    public PaymentRequestClient(
        SerializationHelper serializationHelper,
        HttpClientUseCase httpClientUseCase,
        RestClientConfig restClientConfig
    ) {
        this.serializationHelper = serializationHelper;
        this.httpClientUseCase = httpClientUseCase;
        this.paymentStatusConfig = restClientConfig.getPaymentRequestConfig();
        log.info("Configuracion cargada para payment-status: {}", paymentStatusConfig);
    }

    @Override
    public <T> T execute(
        PaymentRequestRequest params,
        Class<T> responseType
    ) {
        String fintechId = params.getFintechId();
        String applicantId = params.getOperation().getApplicantId();
        Map<String, Object> payload = getPayload(params);
        HttpRequest request = HttpRequest.forApiPrivateResponse(
                paymentStatusConfig.getUrl(),
                paymentStatusConfig.getStatusSuccess(),
                HttpRequest.HttpMethod.POST,
                responseType
            )
            .withBody(payload)
            .withHeaders(Map.of("fintechId", fintechId))
            .withTimeout(
                paymentStatusConfig.getTimeout().getConnect(),
                paymentStatusConfig.getTimeout().getResponse()
            );

        try {
            ApiPrivateResponse<Either<T, ApiPrivateError>> response =
                httpClientUseCase.executeApiPrivateResponse(request);
            Either<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(response.getEstatus())
                    .message("EMPTY_MESSAGE")
                    .build();
            }

            if (detail.isLeft()) {
                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(response.getEstatus())
                .message((error.getCodError() != null)
                        ? error.getCodError() + ":" + error.getMensajeError()
                        : "EMPTY_MESSAGE"
                )
                .build();
        } catch (ApiPrivateException e) {
            throw e;
        } catch (HttpStatusCodeException e) {
            log.error(
                "Error HTTP reportando del cliente {}: {} - {}",
                applicantId,
                e.getStatusCode(),
                e.getMessage()
            );
            throw e;
        } catch (Exception e) {
            log.error("Error reportando del cliente {}: {}", applicantId, e.getMessage());
            throw HttpStatusCodeException.serviceUnavailable("503");
        }
    }

    private Map<String, Object> getPayload(PaymentRequestRequest params) {
        Map<String, Object> paymentStatusRequest = serializationHelper.toMap(params);
        Map<String, Object> operation = serializationHelper.toMap(params.getOperation());
        String signature = serializationHelper.generateSignature(
            params.getOperation(), params.getChannelOrigin()
        );

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

        paymentStatusRequest.remove("fintechId");

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

        return paymentStatusRequest;
    }
}