import { apiFetch } from '@/api/client';

export function fetchOtelStats() {
  return apiFetch<unknown>('/api/otel/api/stats');
}

export function fetchOtelHealth() {
  return apiFetch<unknown>('/api/otel/api/health');
}

interface TraceParams {
  start?: string;
  end?: string;
  service?: string;
  limit?: number;
  offset?: number;
}

export function fetchTraces(params?: TraceParams) {
  const sp = new URLSearchParams();
  if (params?.start) sp.set('start', params.start);
  if (params?.end) sp.set('end', params.end);
  if (params?.service) sp.set('service', params.service);
  if (params?.limit != null) sp.set('limit', String(params.limit));
  if (params?.offset != null) sp.set('offset', String(params.offset));
  const qs = sp.toString();
  return apiFetch<unknown>(`/api/otel/api/traces${qs ? `?${qs}` : ''}`);
}

export function fetchTrace(traceId: string) {
  return apiFetch<unknown>(`/api/otel/api/traces/${encodeURIComponent(traceId)}`);
}

export function fetchLogs(params?: Record<string, string | number | undefined>) {
  const sp = new URLSearchParams();
  if (params) {
    for (const [k, v] of Object.entries(params)) {
      if (v != null) sp.set(k, String(v));
    }
  }
  const qs = sp.toString();
  return apiFetch<unknown>(`/api/otel/api/logs${qs ? `?${qs}` : ''}`);
}

export function fetchMetrics(params?: Record<string, string | number | undefined>) {
  const sp = new URLSearchParams();
  if (params) {
    for (const [k, v] of Object.entries(params)) {
      if (v != null) sp.set(k, String(v));
    }
  }
  const qs = sp.toString();
  return apiFetch<unknown>(`/api/otel/api/metrics${qs ? `?${qs}` : ''}`);
}

export function fetchMetricsTimeseries(metric: string, window?: string, step?: string, service?: string) {
  const sp = new URLSearchParams({ metric });
  if (window) sp.set('window', window);
  if (step) sp.set('step', step);
  if (service) sp.set('service', service);
  return apiFetch<unknown>(`/api/otel/api/metrics/timeseries?${sp.toString()}`);
}
