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

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

export interface ClickHouseStatus {
  reachable: boolean;
  version: string | null;
  uptime: string | null;
  host: string | null;
}

export interface ClickHouseTableInfo {
  name: string;
  engine: string;
  rowCount: number;
  dataSize: string;
  dataSizeBytes: number;
  partitionCount: number;
}

export interface ClickHousePerformance {
  diskSize: string;
  uncompressedSize: string;
  compressionRatio: number;
  totalRows: number;
  partCount: number;
  memoryUsage: string;
  currentQueries: number;
}

export interface ClickHouseQuery {
  queryId: string;
  elapsedSeconds: number;
  memory: string;
  readRows: number;
  query: string;
}

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

export function useClickHouseStatus() {
  const refetchInterval = useRefreshInterval(30_000);
  return useQuery({
    queryKey: ['admin', 'clickhouse', 'status'],
    queryFn: () => adminFetch<ClickHouseStatus>('/clickhouse/status'),
    refetchInterval,
  });
}

export function useClickHouseTables() {
  const refetchInterval = useRefreshInterval(60_000);
  return useQuery({
    queryKey: ['admin', 'clickhouse', 'tables'],
    queryFn: () => adminFetch<ClickHouseTableInfo[]>('/clickhouse/tables'),
    refetchInterval,
  });
}

export function useClickHousePerformance() {
  const refetchInterval = useRefreshInterval(30_000);
  return useQuery({
    queryKey: ['admin', 'clickhouse', 'performance'],
    queryFn: () => adminFetch<ClickHousePerformance>('/clickhouse/performance'),
    refetchInterval,
  });
}

export function useClickHouseQueries() {
  const refetchInterval = useRefreshInterval(5_000);
  return useQuery({
    queryKey: ['admin', 'clickhouse', 'queries'],
    queryFn: () => adminFetch<ClickHouseQuery[]>('/clickhouse/queries'),
    refetchInterval,
  });
}

