import { API_URL } from '@shared/config/env'

interface CsrfResponse {
  header_name: string
  token: string
}

let cachedToken: string | null = null
let inflight: Promise<string> | null = null

export function clearCsrfCache(): void {
  cachedToken = null
  inflight = null
}

export function getCsrfToken(): Promise<string> {
  if (cachedToken) return Promise.resolve(cachedToken)
  if (inflight) return inflight

  inflight = fetch(`${API_URL}/csrf/token`, { credentials: 'include' })
    .then((res) => res.json() as Promise<CsrfResponse>)
    .then((data) => {
      cachedToken = data.token
      inflight = null
      return cachedToken
    })
    .catch((err) => {
      inflight = null
      throw err
    })

  return inflight
}
