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.HttpRequest;
import com.banesco.common.infrastructure.config.RestClientConfig;
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 jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import lombok.extern.slf4j.Slf4j;

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

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

    @Override
    public <T> T execute(Class<T> responseType) {
        SecurityTraceRequest body = securityTraceConfig.getRequest();
        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");
        }
    }
}