import { useQuery } from "@tanstack/react-query";

import type { DashboardResponse, MetaResponse, TargetMetricsResponse } from "../../shared/api";

const queryKeys = {
  dashboard: () => ["dashboard", "24h", 30] as const,
  meta: () => ["meta"] as const,
  metrics: (targetId: string, from: string, to: string, bucket: "1h") =>
    ["metrics", targetId, from, to, bucket] as const,
};

export async function fetchJson<T>(url: string): Promise<T> {
  const response = await fetch(url);
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  return response.json() as Promise<T>;
}

export function useDashboard(refetchInterval: false | number) {
  return useQuery({
    queryFn: () => fetchJson<DashboardResponse>("/api/dashboard?window=24h&recentLimit=30"),
    queryKey: queryKeys.dashboard(),
    refetchInterval,
    refetchIntervalInBackground: false,
  });
}

export function useMeta() {
  return useQuery({
    queryFn: () => fetchJson<MetaResponse>("/api/meta"),
    queryKey: queryKeys.meta(),
    staleTime: Infinity,
  });
}

export function useTargetMetrics(targetId: null | string, from: string, to: string, bucket: "1h") {
  return useQuery({
    enabled: targetId !== null && !!from && !!to,
    queryFn: () => {
      if (targetId === null) throw new Error("未选择目标");
      return fetchJson<TargetMetricsResponse>(
        `/api/targets/${targetId}/metrics?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}&bucket=${bucket}`,
      );
    },
    queryKey: targetId !== null && from && to ? queryKeys.metrics(targetId, from, to, bucket) : ["metrics", "disabled"],
  });
}
