/**
 * Auto-refresh script execution lists (recent / history / script-runs board).
 */
import { onBeforeUnmount } from 'vue'
import { usePageAutoRefresh } from '@/composables/usePageAutoRefresh'
import {
  onScriptExecutionComplete,
  useScriptExecutionQueue,
} from '@/composables/useScriptExecutionQueue'

const FAST_MS = 8000
const SLOW_MS = 30000

export function useScriptExecutionListRefresh(
  refresh: (silent?: boolean) => void | Promise<void>,
  options?: { enabled?: () => boolean },
) {
  const { runningItems } = useScriptExecutionQueue()

  usePageAutoRefresh(
    async () => {
      if (options?.enabled && !options.enabled()) return
      await refresh(true)
    },
    () => (runningItems.value.length > 0 ? FAST_MS : SLOW_MS),
  )

  const offComplete = onScriptExecutionComplete(() => {
    if (options?.enabled && !options.enabled()) return
    void refresh(false)
  })

  onBeforeUnmount(() => {
    offComplete()
  })
}
