import { ref } from 'vue'

const DEFAULT_TTL = 15 * 60 * 1000 // 15 perc

export function useLoadable(ttlMs?: number) {
  const loading = ref(false)
  const error = ref<string | null>(null)
  let _loaded = false
  let _loadedAt = 0

  async function withCache(fn: () => Promise<void>) {
    const effectiveTtl = ttlMs ?? DEFAULT_TTL
    if (_loaded && Date.now() - _loadedAt < effectiveTtl) return
    loading.value = true
    error.value = null
    try {
      await fn()
      _loaded = true
      _loadedAt = Date.now()
    } catch (e) {
      error.value = e instanceof Error ? e.message : String(e)
    } finally {
      loading.value = false
    }
  }

  function invalidate() {
    _loaded = false
  }

  return { loading, error, withCache, invalidate }
}
