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

import com.banesco.common.application.usecase.HttpClientUseCase;
import com.banesco.common.domain.exception.HttpStatusCodeException;
import com.banesco.common.domain.model.ApiResponse;
import com.banesco.common.domain.model.HttpRequest;
import com.banesco.common.infrastructure.config.RestClientConfig;
import com.banesco.module.correspondence.domain.dto.request.CorrespondenceRequest;
import com.banesco.module.security_trace.application.usecase.SecurityTraceUseCase;
import com.banesco.module.security_trace.domain.dto.request.SecurityTraceRequest;
import com.banesco.module.security_trace.domain.model.SecurityTraceConfig;
import com.banesco.module.security_trace.domain.model.SecurityTraceObject;
import io.netty.util.internal.StringUtil;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

@Slf4j
@ApplicationScoped
public class SecurityTraceClient implements SecurityTraceUseCase {
    private final HttpClientUseCase httpClientUseCase;
    private final RestClientConfig restClientConfig;
    private final SecurityTraceConfig securityTraceConfig;

    @Inject
    public SecurityTraceClient(
        HttpClientUseCase httpClientUseCase,
        RestClientConfig restClientConfig
    ) {
        this.httpClientUseCase = httpClientUseCase;
        this.restClientConfig = restClientConfig;
        this.securityTraceConfig = restClientConfig.getSecurityTraceConfig();
        log.info("Configuracion cargada para security-trace: {}", securityTraceConfig);
    }

    @Override
    public <T> T execute(
        CorrespondenceRequest apiRequest,
        Response apiResponse,
        long startTime,
        long endTime,
        Class<T> responseType
    ) {
        SecurityTraceRequest body = getRequest(
            apiRequest, apiResponse,
            startTime, endTime
        );
        HttpRequest request = HttpRequest.forDirectResponse(
                securityTraceConfig.getUrl(),
                HttpRequest.HttpMethod.POST,
                responseType
            )
            .withBody(body)
            .withTimeout(
                securityTraceConfig.getTimeout().getConnect(),
                securityTraceConfig.getTimeout().getResponse()
            );

        log.debug("Request configurado: {}", request);

        try {
            T response = httpClientUseCase.execute(request);

            log.info(
                "Solicitud de traza de seguridad exitosa: {}",
                response.toString().contains("msg=Message sende")
            );

            return response;
        } catch (HttpStatusCodeException e) {
            log.error(
                "Error HTTP ejecutando traza de seguridad: {} - {}",
                e.getStatusCode(),
                e.getMessage()
            );

            throw e;
        } catch (Exception e) {
            log.error("Error ejecutando traza de seguridad: {}", e.getMessage());
            throw HttpStatusCodeException.serviceUnavailable("503");
        }
    }

    private SecurityTraceRequest getRequest(
        CorrespondenceRequest apiRequest,
        Response apiResponse,
        long startTime,
        long endTime
    ) {
        long executedTime = (endTime - startTime);
        int statusHttp = apiResponse.getStatus();
        String recipientId = apiRequest.getRecipientId();
        ApiResponse<?> apiResponseData = (ApiResponse<?>) apiResponse.getEntity();

        return SecurityTraceRequest.builder()
            .sp(securityTraceConfig.getRequest().getSp())
            .codBan(securityTraceConfig.getRequest().getCodBan())
            .codMon(securityTraceConfig.getRequest().getCodMon())
            .codEve(securityTraceConfig.getRequest().getCodEve())
            .codEve2(securityTraceConfig.getRequest().getCodEve2())
            .login(apiRequest.getChannelCode())
            .fecHor(new Date())
            .nacCli(recipientId.substring(0, 1).toUpperCase())
            .cedRifCli(getPartyIdNumber(recipientId.substring(1)))
            .monto(apiRequest.getAmount())
            .objeto(
                restClientConfig.toJsonString(SecurityTraceObject.builder()
                    .RQ(apiRequest)
                    .RS(apiResponseData)
                    .build())
            )
            .tipoRespuesta(statusHttp)
            .msgRespuesta(getStatusMessage(apiResponseData, statusHttp))
            .tiempoRespuesta(executedTime)
            .codFintech(apiRequest.getCustomerReferenceFintechId())
            .nombreFintech(apiRequest.getChannelCode())
            .tipoDispositivo(apiRequest.getDevice().getDeviceType())
            .desDispositivo(apiRequest.getDevice().getDeviceDescription())
            .ipCli(apiRequest.getDevice().getDeviceIp())
            .build();
    }

    private String getStatusMessage(
        ApiResponse<?> apiResponseData,
        int statusHttp
    ) {
        if (apiResponseData != null && apiResponseData.getStatusResponse() != null) {
            String statusCode = apiResponseData.getStatusResponse().getStatusCode();
            String message = apiResponseData.getStatusResponse().getMessage();

            if(StringUtil.isNullOrEmpty(statusCode)) {
                statusCode = String.valueOf(statusHttp);
            }

            return statusCode + "-" + message;
        }

        return null;
    }

    private Integer getPartyIdNumber(String partyId) {
        if (partyId == null || partyId.trim().isEmpty()) {
            return null;
        }

        String digits = partyId.replaceAll("\\D", "");

        if (digits.isEmpty()) {
            return null;
        }

        try {
            return Integer.parseInt(digits);
        } catch (NumberFormatException e) {
            return null;
        }
    }
}