import { ref } from 'vue'

const cache = ref<string[] | null>(null)
const loading = ref(false)

export function useCustomFieldNameSuggestions() {
  const api = useApi()

  async function load(force = false): Promise<string[]> {
    if (cache.value && !force) return cache.value
    if (loading.value) return cache.value ?? []
    loading.value = true
    try {
      const response = await api.get<string[]>('/custom-fields/names')
      if (response.success && Array.isArray(response.data)) {
        cache.value = response.data
      }
      else {
        cache.value = cache.value ?? []
        if (response.error) {
          console.error('[useCustomFieldNameSuggestions] load failed:', response.error)
        }
      }
      return cache.value
    }
    finally {
      loading.value = false
    }
  }

  function invalidate(): void {
    cache.value = null
  }

  return {
    suggestions: cache,
    loading,
    load,
    invalidate,
  }
}
