import type { FetchOptions } from 'ofetch'
import { $fetch, FetchError } from 'ofetch'

export const $XCTN_TOKEN = 'XCTN-TOKEN'

type CitizenFetchOptions = FetchOptions<'json'>

export const $fetchCitizen = async <T>(
  path: string,
  options: CitizenFetchOptions = {}
) => {
  // This wrapper is the single boundary for API base URL, SSR cookie forwarding,
  // and Bearer authentication; pages/composables only provide endpoint details.
  const config = useRuntimeConfig().public
  const apiUrl = (config.NUXT_PUBLIC_API_URL || config.API_URL) as string | undefined
  const token = useCookie<string | null>($XCTN_TOKEN).value
  const requestHeaders = import.meta.server ? useRequestHeaders(['cookie']) : {}

  try {
    // Caller-provided headers are preserved, while a current token always becomes
    // the final Authorization header for this role-specific API client.
    return await $fetch<T>(path, {
      baseURL: apiUrl || undefined,
      ...options,
      headers: {
        accept: 'application/json',
        ...requestHeaders,
        ...(options.headers as Record<string, string> | undefined),
        ...(token ? { Authorization: `Bearer ${token}` } : {})
      }
    })
  } catch (error) {
    // Keep the original FetchError for the caller; this log only adds server-side
    // diagnostics for unexpected backend failures.
    if (error instanceof FetchError && error.response?.status === 500) {
      console.error('[Citizen API Error]', error.data?.message, error.data)
    }

    throw error
  }
}
