package com.banesco.common.infrastructure.config;

import com.banesco.common.domain.model.BusinessConfig;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.quarkus.runtime.annotations.RegisterForReflection;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.microprofile.config.Config;

import java.util.Map;

@Slf4j
@ApplicationScoped
@RegisterForReflection
public class RestClientConfig {

    private final Config config;
    private final ObjectMapper objectMapper;

    private static final String API_BASE = "api.rest-client.";
    private static final String API_DOMAIN_NAME = "bus-legal-customer-product-directory";

    @Inject
    public RestClientConfig(
        Config config,
        ObjectMapper objectMapper
    ) {
        this.config = config;
        this.objectMapper = objectMapper;
    }

    public BusinessConfig getBusLegalCustomerConfig() {
        try {
            String fullConfigName = API_BASE + API_DOMAIN_NAME;
            String json = config.getValue(fullConfigName, String.class);
            log.info("Configurando {}: {}", fullConfigName, json);

            if (json == null || json.trim().isEmpty()) {
                throw new IllegalStateException("Configuracion no encontrada para: " + fullConfigName);
            }

            Map<String, Object> configMap = objectMapper.readValue(json, new TypeReference<>() {});
            return objectMapper.convertValue(configMap, BusinessConfig.class);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException("Formato JSON invalido para " + API_DOMAIN_NAME + ": " + e.getMessage(), e);
        } catch (Exception e) {
            throw new IllegalStateException("Error cargando configuracion del servicio " + API_DOMAIN_NAME + ": " + e.getMessage(), e);
        }
    }
}