/**
 * Composable for fetching enabled OAuth providers
 *
 * This composable automatically fetches and caches the list of OAuth providers
 * that are enabled based on whether their required environment variables are set.
 * The cache persists across component instances and page navigations.
 *
 * @example
 * const { socialProviders, loading } = useSocialProviders()
 * // socialProviders.value is ['github', 'google'] or []
 * // loading.value is true while fetching
 */
export const useSocialProviders = () => {
  // Cache for providers list - persists across component instances
  const cachedProviders = useState<string[]>('social:providers', () => [])

  const { data, pending } = useApiFetch<{ providers: string[] }>('/api/auth/social-providers', {
    server: false
  })

  // Extract providers from response and update cache
  const extractProviders = (response: unknown): string[] => {
    if (!response || typeof response !== 'object') return []
    // Handle both ApiResponse and extracted data formats
    if ('data' in response && response.data && typeof response.data === 'object' && response.data !== null && 'providers' in response.data) {
      return (response.data as { providers: string[] }).providers || []
    }
    if ('providers' in response && Array.isArray((response as { providers: string[] }).providers)) {
      return (response as { providers: string[] }).providers || []
    }
    return []
  }

  // Update cache when data arrives
  watch(data, (response) => {
    const providers = extractProviders(response)
    if (providers.length > 0) {
      cachedProviders.value = providers
    }
  }, { immediate: true })

  const socialProviders = computed<string[]>(() => {
    // Return cached value if available, otherwise extract from current response
    if (cachedProviders.value.length > 0) {
      return cachedProviders.value
    }

    return extractProviders(data.value)
  })

  return {
    socialProviders,
    loading: pending
  }
}
