import type { AppError } from '@dev.smartpricing/message-composer-utils/types'
import { useAppContextStore } from '@/stores/appContext'
import { resolveErrorToast } from '~/composables/apiErrorMessages'

function assertAppError(data: unknown): data is AppError {
  if (typeof data !== 'object' || data === null) {
    return false
  }
  if ('code' in data && 'error' in data && 'statusCode' in data) {
    return true
  }
  return false
}

export const apiClient = createApiClient({
  baseURL: useRuntimeConfig().public.COMPOSER_API_URL as string,
  csrf: {
    // Same key and derivation as platform-layer's own client: the host sets the
    // full cookie name (env-suffixed: smt_csrf / smt_csrf_stage / smt_csrf_dev).
    cookieName: (useRuntimeConfig().public.CSRF_COOKIE_NAME as string) || 'smt_csrf',
  },
  auth: {
    refreshBaseURL:
      (useRuntimeConfig().public.BACKEND_BASE_URL as string) ||
      (useRuntimeConfig().public.PLATFORM_URL as string),
    platformURL: useRuntimeConfig().public.PLATFORM_URL as string,
    // The composer backend answers a dead access token with @fastify/jwt's flat
    // body (`code: FST_JWT_*` at top level), never the platform's nested
    // `error.code: session.*` that the default predicate looks for. Refresh on
    // any 401, as Connect's client does; the retry decides.
    shouldRefresh: (status) => status === 401,
    onRefreshFailed: () => {
      useNuxtApp().callHook('composer:auth-error', { statusCode: 401 })
    },
  },
  // No Organization header: every request names its Organization itself, in
  // the query, in the body or through the resource it acts on (ADR 0014).
  // No WABA header either: a submission names its WABA in the body (ADR 0015).
  onRequest({ options }) {
    const store = useAppContextStore()

    if (store.product) {
      options.headers.set('sm-product', store.product)
    }
    if (store.default_tags && store.default_tags.length > 0) {
      options.headers.set('sm-default-tags', store.default_tags.join(','))
    }
  },
  onResponseError({ response, options }) {
    // A 401 that reaches here survived the refresh attempt (or its retry): the
    // session is dead. platform-layer only calls onRefreshFailed for its own
    // `session.*` codes, so tell the host here for the composer's `FST_JWT_*`.
    if (response.status === 401) {
      useNuxtApp().callHook('composer:auth-error', { statusCode: 401 })
      return
    }
    if ((options as { _skipErrorToast?: boolean })._skipErrorToast) return

    const t = useNuxtApp().$i18n.t
    const code = assertAppError(response._data) ? response._data.code : undefined
    const toast = resolveErrorToast({ status: response.status, code }, t)
    useToast().add({ ...toast, color: 'error' })
  },
})
