package com.banesco.commons.config;

import com.banesco.commons.exceptions.BanRuntimeException;
import com.banesco.commons.helper.JsonHelper;
import com.banesco.commons.model.SoapEndpoint;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.ConfigProvider;
import org.eclipse.microprofile.config.inject.ConfigProperty;

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

/**
 * Define Base Configurations to Load resources required to invoke Banesco Soap Service
 */
@Slf4j
public class BaseAppConfig<T> {


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

    @ConfigProperty(name = "soap.domain.current")
    public String SOAP_CURRENT_DOMAIN;

    @Getter
    protected JsonHelper jsonHelper;

    @Getter
    protected Config env;

    public BaseAppConfig(JsonHelper jsonHelper) {
        this.jsonHelper = jsonHelper;
        this.env = ConfigProvider.getConfig();
    }


    public SoapEndpoint loadSoapClientConfig(String soapClientName) {

        String soapConfig = env.getValue(soapClientName, String.class);
        log.info("Loading SoapConfig:{} -> {}", soapClientName, soapConfig);
        if (soapConfig == null) {
            throw new BanRuntimeException("SOAP01", "SoapConfig is empty");
        }
        return jsonHelper.getObjectFromJson(soapConfig, SoapEndpoint.class);
    }

    /**
     * Allow to get Soap UrlBase to request domainKey
     * Required: env property 'soap.domain.<srcAppId>' defined as http://<ip or domain>
     *
     * @param domainKey String
     * @return
     */

    public String getDomainConfig(String domainKey) {

        String domain = SOAP_DOMAINS.get(domainKey);
        if (domain == null) {
            domain = env.getValue("soap.domains.".concat(domainKey), String.class);
            log.info("Loading Domain:{} -> {}", domainKey, domain);
            if (domain == null) {
                throw new BanRuntimeException("CONF01", "domain invalid or bad configured: %s".formatted(domainKey));
            }
            SOAP_DOMAINS.put(domainKey, domain);
        }
        return domain;
    }

}
