package net.siegeln.cameleer.saas.identity;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.io.File;

@Configuration
public class LogtoConfig {

    private static final Logger log = LoggerFactory.getLogger(LogtoConfig.class);
    private static final String BOOTSTRAP_FILE = "/data/bootstrap/logto-bootstrap.json";

    @Value("${cameleer.identity.logto-endpoint:}")
    private String logtoEndpoint;

    @Value("${cameleer.identity.m2m-client-id:}")
    private String m2mClientId;

    @Value("${cameleer.identity.m2m-client-secret:}")
    private String m2mClientSecret;

    @Value("${cameleer.identity.server-endpoint:http://cameleer3-server:8081}")
    private String serverEndpoint;

    private String tradAppId;

    @PostConstruct
    public void init() {
        if (isConfigured()) return;

        // Fall back to bootstrap file for M2M credentials + trad app ID
        try {
            File file = new File(BOOTSTRAP_FILE);
            if (file.exists()) {
                JsonNode node = new ObjectMapper().readTree(file);
                if ((m2mClientId == null || m2mClientId.isEmpty()) && node.has("m2mClientId")) {
                    m2mClientId = node.get("m2mClientId").asText();
                }
                if ((m2mClientSecret == null || m2mClientSecret.isEmpty()) && node.has("m2mClientSecret")) {
                    m2mClientSecret = node.get("m2mClientSecret").asText();
                }
                if (node.has("tradAppId")) {
                    tradAppId = node.get("tradAppId").asText();
                }
                log.info("Loaded M2M credentials from bootstrap file");
            }
        } catch (Exception e) {
            log.warn("Failed to read bootstrap config for M2M credentials: {}", e.getMessage());
        }
    }

    public String getLogtoEndpoint() { return logtoEndpoint; }
    public String getM2mClientId() { return m2mClientId; }
    public String getM2mClientSecret() { return m2mClientSecret; }
    public String getServerEndpoint() { return serverEndpoint; }
    public String getTradAppId() { return tradAppId; }

    public boolean isConfigured() {
        return logtoEndpoint != null && !logtoEndpoint.isEmpty()
                && m2mClientId != null && !m2mClientId.isEmpty()
                && m2mClientSecret != null && !m2mClientSecret.isEmpty();
    }
}
