import { keepPreviousData, useQuery } from '@tanstack/react-query';
import { adminApi } from '../apis';
import { adminKeys } from '../keys';
import { ADMIN_CONFIG_STALE_TIME, ADMIN_GC_TIME, ADMIN_PAGE_SIZE } from '../constants';

/**
 * The audited change history for one config key (newest first) — finance proves the rate in effect at any
 * past moment. `enabled` gates the fetch to when the drawer is open (a closed drawer never fetches).
 */
export function useConfigChangeHistory(key: string | null, page = 1, enabled = true) {
  return useQuery({
    queryKey: adminKeys.configHistory(key ?? '', { page, pageSize: ADMIN_PAGE_SIZE }),
    queryFn: () => adminApi.getConfigHistory(key!, { page, pageSize: ADMIN_PAGE_SIZE }),
    enabled: enabled && !!key,
    staleTime: ADMIN_CONFIG_STALE_TIME,
    gcTime: ADMIN_GC_TIME,
    placeholderData: keepPreviousData,
  });
}
