package com.banesco.infrastructure.rest.mappers;

import com.banesco.common.application.exception.BanBackendException;
import com.banesco.common.infraestructure.helpers.JsonHelper;
import com.banesco.commons.config.AppConf;
import com.banesco.domain.models.CurrentState;
import com.banesco.infrastructure.dtos.osb.MsgRqHdr;
import jakarta.enterprise.context.ApplicationScoped;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.microprofile.config.Config;

import java.util.HashMap;
import java.util.Map;


@ApplicationScoped
@Slf4j
public class SoapHeaderMapper {

    public final Map<String, MsgRqHdr> SOAP_HEADERS = new HashMap<>();

    private final Config configEnv;

    public SoapHeaderMapper(AppConf appConf) {
        configEnv = appConf.getConfigEnv();
    }

    /**
     * Permite obtener el Request Header de una operacion hacia servicios SOAP
     *
     * @param operationName
     * @return
     */
    public MsgRqHdr getHeaderBySrcAppId(String operationName, CurrentState currentState) {

        MsgRqHdr msgRqHdr = SOAP_HEADERS.get(operationName);
        String msgRqHdrEnvName = "api.rest-client." + operationName + ".msgRqHdr";
        try {
            if (msgRqHdr == null) {
                String soapHeaderStr = configEnv.getValue("api.rest-client." + operationName + ".msgRqHdr", String.class);
                msgRqHdr = JsonHelper.getObjectFromJson(
                        soapHeaderStr,
                        MsgRqHdr.class);
                log.info("[SOAP HEADER loaded]:{} -> {}", operationName, soapHeaderStr);

                if (msgRqHdr == null) {
                    throw new BanBackendException("CONF02", msgRqHdrEnvName + " invalid or bad configured.");
                }

                SOAP_HEADERS.put(operationName, msgRqHdr);
            }

            msgRqHdr = msgRqHdr.clone();
            msgRqHdr.setRequestId(currentState.requestId());
            msgRqHdr.setMessageDate(currentState.date());
            msgRqHdr.setMessageTime(currentState.time());
            msgRqHdr.getNetworkTrnInfo().get(0).setTransactionDate(currentState.date());
            msgRqHdr.getNetworkTrnInfo().get(0).setTransactionTime(currentState.time());


            return msgRqHdr;
        } catch (Exception e) {
            throw new BanBackendException("CONF02", msgRqHdrEnvName + " invalid or bad configured.");
        }

    }

}
