import { useQuery } from "@tanstack/react-query";
import { useSyncExternalStore } from "react";
import { api, type ListActivityParams, type PaginatedResponse } from "@/lib/api";
import { useAppStore } from "@/store";
import type { Activity } from "@/types";

/**
 * Lists activity. Polls every 30s when a backend is configured (so the
 * Activity Log page reflects new events without a manual refresh); in
 * sample-data mode it returns the in-memory store directly.
 */
export function useActivity(params: ListActivityParams = {}) {
  const fallback = useSyncExternalStore(
    (cb) => useAppStore.subscribe(cb),
    () => useAppStore.getState().activity,
    () => useAppStore.getState().activity
  );

  const q = useQuery<PaginatedResponse<Activity>>({
    queryKey: ["activity", params],
    queryFn: () => api.listActivity<Activity>(params),
    enabled: api.isConfigured,
    refetchInterval: api.isConfigured ? 30_000 : false,
  });

  if (!api.isConfigured) {
    return {
      data: {
        items: fallback,
        total: fallback.length,
        returned: fallback.length,
        has_more: false,
      } satisfies PaginatedResponse<Activity>,
      isLoading: false,
      isError: false,
      error: null,
      refetch: () => Promise.resolve(),
    } as const;
  }
  return q;
}
