import { AUTH_COOKIE_NAME, AUTH_COOKIE_MAX_AGE } from '@/lib/constants/auth'
import { UserRole } from '@/types/auth'

/** Write the JWT access token to the browser cookie */
export function setAuthCookie(token: string): void {
  if (typeof document === 'undefined') return
  const expires = new Date(Date.now() + AUTH_COOKIE_MAX_AGE * 1000).toUTCString()
  document.cookie = `${AUTH_COOKIE_NAME}=${token}; path=/; expires=${expires}; SameSite=Lax`
}

/** Remove the JWT access token cookie */
export function clearAuthCookie(): void {
  if (typeof document === 'undefined') return
  document.cookie = `${AUTH_COOKIE_NAME}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax`
}

/** Read the JWT token value from the browser cookie */
export function getAuthToken(): string | null {
  if (typeof document === 'undefined') return null
  const match = document.cookie
    .split('; ')
    .find((row) => row.startsWith(`${AUTH_COOKIE_NAME}=`))
  return match ? match.split('=')[1] : null
}

/**
 * Lightweight base64 decode of the JWT payload — no crypto, no signature
 * verification. Used ONLY in proxy.ts for optimistic role-based routing.
 */
export function decodeTokenRole(token: string): UserRole | null {
  try {
    const payloadBase64 = token.split('.')[1]
    if (!payloadBase64) return null
    // Pad base64 if needed
    const padded = payloadBase64.replace(/-/g, '+').replace(/_/g, '/')
    const json = atob(padded)
    const payload = JSON.parse(json) as { role?: string }
    return (payload.role as UserRole) ?? null
  } catch {
    return null
  }
}
