package com.banesco.common.infrastructure.config;

import com.banesco.common.domain.model.AppIdConfig;
import com.banesco.module.legal_customer_product_directory.domain.dto.request.LegalCustomerProductDirectoryRequest;
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.List;
import java.util.Map;

@Slf4j
@ApplicationScoped
@RegisterForReflection
public class ApiAllowedConfig {

    private final Config config;
    private final ObjectMapper objectMapper;

    private static final String API_ALLOWED_BASE = "api.allowed.";
    private static final String API_ALLOWED_APP_ID_NAME = "app-id";

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

    public List<AppIdConfig> getAppIdAllowed() {
        try {
            String fullConfigName = API_ALLOWED_BASE + API_ALLOWED_APP_ID_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);
            }

            List<Map<String, Object>> configList = objectMapper.readValue(json, new TypeReference<>() {});

            return configList.stream()
                .map(this::mapToAppIdConfig)
                .toList();
        } catch (Exception e) {
            return List.of();
        }
    }

    private AppIdConfig mapToAppIdConfig(Map<String, Object> configMap) {
        AppIdConfig appIdConfig = new AppIdConfig();
        String appId = (String) configMap.get("appId");

        appIdConfig.setAppId(appId);

        if (configMap.containsKey("request")) {
            Object requestObj = configMap.get("request");
            LegalCustomerProductDirectoryRequest request = objectMapper.convertValue(
                requestObj, LegalCustomerProductDirectoryRequest.class
            );

            appIdConfig.setRequest(request);
        }

        return appIdConfig;
    }
}