/**
 * Base API service using Nuxt's built-in $fetch.
 * Replaces the old axios-based Service.js + config/index.js + plugins/axios.js.
 *
 * NOTE: This uses $fetch directly with runtime config, avoiding composable
 * dependencies that can fail outside setup context.
 */

export function useApi() {
  const config = useRuntimeConfig()
  const baseURL = config.public.apiBaseUrl as string

  async function apiFetch<T = unknown>(
    url: string,
    options: Parameters<typeof $fetch>[1] = {},
  ): Promise<T> {
    // Get locale - try i18n first, fallback to cookie, fallback to 'en'
    let currentLocale = 'en'
    try {
      const nuxtApp = useNuxtApp()
      currentLocale = nuxtApp.$i18n?.locale?.value || 'en'
    } catch {
      // Not in Nuxt context
    }

    const headers: Record<string, string> = {
      Localization: currentLocale,
      ...(options.headers as Record<string, string> || {}),
    }

    // Get auth token from cookie directly (works everywhere)
    let token: string | null = null
    try {
      token = useCookie('auth_token').value
    } catch {
      // Not in Nuxt context
    }

    if (token) {
      headers.Authorization = `Bearer ${token}`
    }

    // Add lang param to GET requests
    if (!options.method || options.method.toUpperCase() === 'GET') {
      const params = (options.params || options.query || {}) as Record<string, unknown>
      params.lang = currentLocale
      options.query = params
    }

    return $fetch<T>(url, {
      baseURL,
      ...options,
      headers,
      onResponseError({ response }) {
        const code = response.status

        if (code === 401) {
          // Clear auth cookie
          try {
            const tokenCookie = useCookie('auth_token')
            tokenCookie.value = null
          } catch { /* ignore */ }
          navigateTo('/auth/login')
        }

        if (code === 403) {
          navigateTo('/unauth')
        }
      },
    })
  }

  return { apiFetch, baseURL }
}
