package com.banesco.commons.config;

import com.banesco.common.application.exception.BanRuntimeException;
import com.banesco.common.domain.dto.bian.device.DateHelper;
import com.banesco.common.domain.dto.bian.device.JsonHelper;
import com.banesco.common.domain.dto.bian.device.RequestHelper;
import com.banesco.common.domain.model.ApiConfig;
import com.banesco.commons.exceptions.BanConfigException;
import com.banesco.domain.models.CurrentState;
import jakarta.inject.Singleton;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.ConfigProvider;

import java.time.LocalDateTime;
import java.util.NoSuchElementException;


@Singleton
@Getter
@Slf4j
public class AppConf {

    private static AppConf _INSTANCE;

    private final String appSourceId;
    private final Config configEnv;
    private final RequestHelper requestHelper;

    public String soapDomainCurrent;

    DateHelper dateHelper = DateHelper.getInstance();

    public static void getInstance() {

        synchronized (AppConf.class) {
            if (_INSTANCE == null) {
                log.info("AppConf getInstance-->");
                _INSTANCE = new AppConf();
            }
        }
    }

    public AppConf() {

        log.info("NEW INSTANCE AppConf**********************************");
        try {

            configEnv = ConfigProvider.getConfig();

            requestHelper = new RequestHelper();

            soapDomainCurrent = configEnv.getValue("soap.domain.current", String.class);

            appSourceId = configEnv.getValue("api.source-id", String.class);

            _INSTANCE = this;
        } catch (NoSuchElementException e) {
            String errorMessage = "[ERROR CONFIG]: [%s]".formatted(e.getMessage());
            log.error(errorMessage);
            throw new BanConfigException(errorMessage);
        } catch (Exception e) {
            String errorMessage = "[ERROR CONFIG]: [%s]".formatted(e.getMessage());
            log.error(errorMessage);
            throw new BanConfigException(errorMessage);
        }

    }


    public ApiConfig loadApiConfig(String apiName) {

        try {

            log.info("Loading APIConfig with key:{}", apiName);
            String apiConfig = configEnv.getValue(apiName, String.class);
            return JsonHelper.getObjectFromJson(apiConfig, ApiConfig.class);
        } catch (Exception e) {
            log.error("Error Loading API Config: {} -> {}", apiName, e.getMessage());
            throw new BanRuntimeException(StatusCodes.INTERNAL_ERROR);
        }

    }


    public CurrentState getCurrentState(String requestId) {

        LocalDateTime now = dateHelper.getCurrentDateTime();
        return new CurrentState(
                dateHelper.getDate(now),
                dateHelper.getTime(now),
                requestId
        );
    }

}
