import { onUnmounted, ref } from 'vue'

/**
 * Creates an auto-refresh interval that can be started, stopped, and automatically cleaned up
 * @param callback - The function to call on each interval
 * @param intervalMs - Interval in milliseconds (default: 5 minutes)
 * @returns Control functions for the interval
 */
export function useAutoRefresh(callback: () => void, intervalMs = 5 * 60 * 1000) {
  const intervalId = ref<number | null>(null)
  const isRunning = ref(false)

  const stop = () => {
    if (intervalId.value !== null) {
      clearInterval(intervalId.value)
      intervalId.value = null
      isRunning.value = false
    }
  }

  const start = () => {
    stop()
    intervalId.value = window.setInterval(callback, intervalMs)
    isRunning.value = true
  }

  const restart = () => {
    start()
  }

  // Clean up on unmount
  onUnmounted(() => {
    stop()
  })

  return {
    start,
    stop,
    restart,
    isRunning,
  }
}

/**
 * Creates a timer that updates a "now" ref every second for relative time displays
 * @returns The current timestamp ref and control functions
 */
export function useNowTimer() {
  const now = ref(Math.floor(Date.now() / 1000))
  let timerId: number | undefined

  const start = () => {
    stop()
    timerId = window.setInterval(() => {
      now.value = Math.floor(Date.now() / 1000)
    }, 1000)
  }

  const stop = () => {
    if (timerId !== undefined) {
      clearInterval(timerId)
      timerId = undefined
    }
  }

  onUnmounted(() => {
    stop()
  })

  return {
    now,
    start,
    stop,
  }
}
