package com.banesco.common.infrastructure.config;

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

import java.util.Map;

@Slf4j
@ApplicationScoped
@RegisterForReflection
public class RestClientConfig {

    private final Config config;
    private final ObjectMapper objectMapper;

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

    public BusConfig getBusLegalCustomerConfig() {
        try {
            String json = config.getValue("api.rest-client.bus-legal-customer-product-directory", String.class);
            log.info("Configurando bus-legal-customer-product-directory: {}", json);

            if (json == null || json.trim().isEmpty()) {
                throw new IllegalStateException("Configuración requerida no encontrada para: api.rest-client.bus-legal-customer-product-directory");
            }

            Map<String, Object> configMap = objectMapper.readValue(json, new TypeReference<>() {});
            return objectMapper.convertValue(configMap, BusConfig.class);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException("Formato JSON inválido en la configuración: api.rest-client.bus-legal-customer-product-directory", e);
        } catch (Exception e) {
            throw new IllegalStateException("Error cargando configuración del servicio", e);
        }
    }

    public RegisterSecurityConfig getRegisterSecurityConfig() {
        try {
            String json = config.getValue("api.rest-client.register-security", String.class);
            log.info("Configurando register-security: {}", json);

            if (json == null || json.trim().isEmpty()) {
                throw new IllegalStateException("Configuración requerida no encontrada para: api.rest-client.register-security");
            }

            Map<String, Object> configMap = objectMapper.readValue(json, new TypeReference<>() {});
            return objectMapper.convertValue(configMap, RegisterSecurityConfig.class);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException("Formato JSON inválido en la configuración: api.rest-client.register-security", e);
        } catch (Exception e) {
            throw new IllegalStateException("Error cargando configuración del servicio register-security", e);
        }
    }
}
