export function useApi() {
  const config = useRuntimeConfig()
  const token = useCookie<string | null>('may_projet_token', { maxAge: 60 * 60 * 24 * 30 })

  async function request<T>(path: string, options: Parameters<typeof $fetch>[1] = {}): Promise<T> {
    try {
      return await $fetch<T>(path, {
        baseURL: config.public.apiBase,
        ...options,
        headers: {
          Accept: 'application/json',
          ...(options?.headers as Record<string, string> | undefined),
          ...(token.value ? { Authorization: `Bearer ${token.value}` } : {})
        }
      })
    } catch (e: any) {
      if (e?.response?.status === 401) {
        token.value = null
        await navigateTo('/login')
      }
      throw e
    }
  }

  return { request, token }
}
