package net.siegeln.cameleer.saas.config;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.List;
import java.util.Map;

@RestController
public class PublicConfigController {

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

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

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

    private final ObjectMapper objectMapper = new ObjectMapper();

    private static final List<String> SCOPES = List.of(
            "platform:admin",
            "tenant:manage",
            "billing:manage",
            "team:manage",
            "apps:manage",
            "apps:deploy",
            "secrets:manage",
            "observe:read",
            "observe:debug",
            "settings:manage",
            "server:admin",
            "server:operator",
            "server:viewer"
    );

    @GetMapping("/api/config")
    public Map<String, Object> config() {
        JsonNode bootstrap = readBootstrapFile();

        String clientId = spaClientId;
        if (clientId == null || clientId.isEmpty()) {
            clientId = bootstrap != null && bootstrap.has("spaClientId")
                    ? bootstrap.get("spaClientId").asText() : "";
        }

        String apiResource = bootstrap != null && bootstrap.has("apiResourceIndicator")
                ? bootstrap.get("apiResourceIndicator").asText() : "";

        // Use public endpoint for browser redirects (not Docker-internal URL)
        String endpoint = logtoPublicEndpoint;
        if (endpoint == null || endpoint.isEmpty()) {
            endpoint = "http://localhost:3001";
        }

        return Map.of(
                "logtoEndpoint", endpoint,
                "logtoClientId", clientId != null ? clientId : "",
                "logtoResource", apiResource,
                "scopes", SCOPES
        );
    }

    private JsonNode readBootstrapFile() {
        try {
            File file = new File(BOOTSTRAP_FILE);
            if (file.exists()) {
                return objectMapper.readTree(file);
            }
        } catch (Exception e) {
            log.warn("Failed to read bootstrap config: {}", e.getMessage());
        }
        return null;
    }
}
