import { useQuery } from '@tanstack/react-query';
import { adminFetch } from './admin-api';
import { useRefreshInterval } from '../use-refresh-interval';

// ── Types ──────────────────────────────────────────────────────────────

export interface ServerMetricCatalogEntry {
  metricName: string;
  metricType: string;
  statistics: string[];
  tagKeys: string[];
}

export interface ServerInstanceInfo {
  serverInstanceId: string;
  firstSeen: string;
  lastSeen: string;
}

export interface ServerMetricPoint {
  t: string;
  v: number;
}

export interface ServerMetricSeries {
  tags: Record<string, string>;
  points: ServerMetricPoint[];
}

export interface ServerMetricQueryResponse {
  metric: string;
  statistic: string;
  aggregation: string;
  mode: string;
  stepSeconds: number;
  series: ServerMetricSeries[];
}

export interface ServerMetricQueryRequest {
  metric: string;
  statistic?: string | null;
  from: string;
  to: string;
  stepSeconds?: number | null;
  groupByTags?: string[] | null;
  filterTags?: Record<string, string> | null;
  aggregation?: string | null;
  mode?: string | null;
  serverInstanceIds?: string[] | null;
}

// ── Range helper ───────────────────────────────────────────────────────

/**
 * Time range driving every hook below. Callers pass the window they want
 * to render; the hooks never invent their own "now" — that's the job of
 * the global time-range control.
 */
export interface ServerMetricsRange {
  from: Date;
  to: Date;
}

function serializeRange(range: ServerMetricsRange) {
  return {
    from: range.from.toISOString(),
    to: range.to.toISOString(),
  };
}

// ── Query Hooks ────────────────────────────────────────────────────────

export function useServerMetricsCatalog(range: ServerMetricsRange) {
  const refetchInterval = useRefreshInterval(60_000);
  const { from, to } = serializeRange(range);
  return useQuery({
    queryKey: ['admin', 'server-metrics', 'catalog', from, to],
    queryFn: () => {
      const params = new URLSearchParams({ from, to });
      return adminFetch<ServerMetricCatalogEntry[]>(`/server-metrics/catalog?${params}`);
    },
    refetchInterval,
  });
}

export function useServerMetricsInstances(range: ServerMetricsRange) {
  const refetchInterval = useRefreshInterval(60_000);
  const { from, to } = serializeRange(range);
  return useQuery({
    queryKey: ['admin', 'server-metrics', 'instances', from, to],
    queryFn: () => {
      const params = new URLSearchParams({ from, to });
      return adminFetch<ServerInstanceInfo[]>(`/server-metrics/instances?${params}`);
    },
    refetchInterval,
  });
}

/**
 * Generic time-series query against the server_metrics table.
 *
 * The caller owns the window — passing the globally-selected range keeps
 * every panel aligned with the app-wide time control and allows inspection
 * of historical windows, not just "last N seconds from now".
 */
export function useServerMetricsSeries(
  request: Omit<ServerMetricQueryRequest, 'from' | 'to'>,
  range: ServerMetricsRange,
  opts?: { enabled?: boolean },
) {
  const refetchInterval = useRefreshInterval(30_000);
  const { from, to } = serializeRange(range);
  return useQuery({
    queryKey: ['admin', 'server-metrics', 'query', request, from, to],
    queryFn: () => {
      const body: ServerMetricQueryRequest = { ...request, from, to };
      return adminFetch<ServerMetricQueryResponse>('/server-metrics/query', {
        method: 'POST',
        body: JSON.stringify(body),
      });
    },
    refetchInterval,
    enabled: opts?.enabled ?? true,
  });
}
