import { PrometheusClient } from "./prometheus.js";
import { LokiClient } from "./loki.js";
export function createResolvers(db, config) {
    const prometheus = new PrometheusClient(config.prometheusUrl);
    const loki = new LokiClient(config.lokiUrl);
    return {
        Query: {
            environmentStatus: async (_parent, { tenantId }) => {
                const row = await db
                    .selectFrom("environment_status")
                    .selectAll()
                    .where("tenantId", "=", tenantId)
                    .executeTakeFirst();
                if (!row)
                    return null;
                return {
                    ...row,
                    configDriftDetected: !!row.configDriftDetected,
                    tlsCertValid: row.tlsCertValid === null ? null : !!row.tlsCertValid,
                    domainResolves: row.domainResolves === null ? null : !!row.domainResolves,
                };
            },
            environmentPods: async (_parent, { tenantId }) => {
                const rows = await db
                    .selectFrom("environment_pods")
                    .selectAll()
                    .where("tenantId", "=", tenantId)
                    .execute();
                return rows.map((row) => ({
                    ...row,
                    ready: !!row.ready,
                    service: row.service === "OTHER" ? null : row.service,
                }));
            },
            environmentEvents: async (_parent, { tenantId, limit }) => {
                const cappedLimit = Math.min(limit ?? 50, 200);
                return db
                    .selectFrom("environment_events")
                    .selectAll()
                    .where("tenantId", "=", tenantId)
                    .orderBy("timestamp", "desc")
                    .limit(cappedLimit)
                    .execute();
            },
            // Prometheus proxies — delegate directly
            cpuUsage: async (_parent, { tenantId, range }) => prometheus.cpuUsage(tenantId, range ?? "FIVE_MIN"),
            memoryUsage: async (_parent, { tenantId, range }) => prometheus.memoryUsage(tenantId, range ?? "FIVE_MIN"),
            podRestartRate: async (_parent, { tenantId, range }) => prometheus.podRestartRate(tenantId, range ?? "FIVE_MIN"),
            httpRequestRate: async (_parent, { tenantId, range }) => prometheus.httpRequestRate(tenantId, range ?? "FIVE_MIN"),
            httpLatency: async (_parent, { tenantId, range }) => prometheus.httpLatency(tenantId, range ?? "FIVE_MIN"),
            // Loki proxies
            logs: async (_parent, { tenantId, service, since, limit, }) => loki.logs(tenantId, service ?? null, since ?? "FIVE_MIN", limit ?? 100),
            errorLogs: async (_parent, { tenantId, since, limit, }) => loki.errorLogs(tenantId, since ?? "FIVE_MIN", limit ?? 100),
        },
    };
}
