import { useRef } from 'react'
import { useDidShow } from '@tarojs/taro'
import { shouldRefresh, type ResourceKey } from '@/store/dataBus'

/**
 * Refresh a page's data on `onShow`, but only when it is actually stale.
 *
 * The very first `onShow` (fired right after mount) is skipped because the page
 * already loads on mount. Afterwards `refresh` runs only when the resource was
 * marked stale by a mutation elsewhere, or its TTL has elapsed. `refresh` should
 * be a *silent* reload (keep the current content visible) so returning to a page
 * never flashes a blank/loading state.
 */
export function useRefreshOnShow(key: ResourceKey, refresh: () => void, ttlMs?: number) {
  const firstShow = useRef(true)

  useDidShow(() => {
    if (firstShow.current) {
      firstShow.current = false
      return
    }
    if (shouldRefresh(key, ttlMs)) refresh()
  })
}
