package com.banesco.infrastructure.rest;

import com.banesco.common.domain.dto.bian.device.LoggerHelper;
import com.banesco.common.domain.model.ApiConfig;
import com.banesco.commons.config.AppConf;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.microprofile.rest.client.RestClientBuilder;

import java.net.URI;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;


@ApplicationScoped
@Slf4j
public class RegisterSecurityAdapter implements RegisterSecurityPort {

    private final RegisterSecurityRestClient restClient;

    private final String registerSecuritySP;
    private final String registerSecurityEventCod;
    private final String registerSecurityBankCod;
    private final String registerSecurityCurCOd;


    @Inject
    public RegisterSecurityAdapter(AppConf appConf) {

        ApiConfig apiConfig = appConf.loadApiConfig("api.rest-client.register-security");

        restClient = RestClientBuilder.newBuilder().baseUri(
                        URI.create(apiConfig.getUrl())
                ).
                connectTimeout(apiConfig.getTimeout().getConnect(), TimeUnit.MILLISECONDS)
                .readTimeout(apiConfig.getTimeout().getResponse(), TimeUnit.MILLISECONDS)
                .build(RegisterSecurityRestClient.class);

        registerSecuritySP = apiConfig.getConfig().get("sp");
        registerSecurityEventCod = apiConfig.getConfig().get("eventCod");
        registerSecurityBankCod = apiConfig.getConfig().get("bankCod");
        registerSecurityCurCOd = apiConfig.getConfig().get("curCod");
    }


    public void writeTrace(String requestId, RegisterSecurityRq request) {

        request.setSp(registerSecuritySP);
        request.setCodEve(registerSecurityEventCod);
        request.setCodEve2(registerSecurityEventCod);
        request.setCodBan(registerSecurityBankCod);
        request.setCodMon(registerSecurityCurCOd);
        log.info(LoggerHelper.buildInfoPrivateRequest(requestId, "REGISTER_SECURITY", request));

        CompletableFuture.supplyAsync(() -> {
            // Simulate some processing
            try {
                Response responseHttp = restClient.invoke(request);
                Object response = responseHttp.readEntity(Object.class);
                log.info(LoggerHelper.buildInfoPrivateResponse(requestId, "REGISTER_SECURITY", response != null ? response.toString() : "null"));
            } catch (Exception e) {
                log.error(LoggerHelper.buildError("REGISTER_SECURITY - " + requestId, "Error calling API: " + e.getMessage()));
                log.error("Error writing trace: {}", e.getMessage());
            }
            return null;
        });

    }


}
