/**
 * Shared utilities used across mizan-react.
 */

/** Default CSRF cookie name. Configurable via MizanProvider. */
let _csrfCookieName = 'csrftoken'

/** Default CSRF header name. Configurable via MizanProvider. */
let _csrfHeaderName = 'X-CSRFToken'

export function configureCsrf(cookieName: string, headerName: string): void {
    _csrfCookieName = cookieName
    _csrfHeaderName = headerName
}

export function getCsrfCookieName(): string {
    return _csrfCookieName
}

export function getCsrfHeaderName(): string {
    return _csrfHeaderName
}

/** Extract CSRF token from cookies. Returns null during SSR. */
export function getCSRFToken(): string | null {
    if (typeof document === 'undefined') return null
    const match = document.cookie.match(new RegExp(`${_csrfCookieName}=([^;]+)`))
    return match?.[1] ?? null
}
