const toBase64 = (value: string) =>
  value.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(value.length / 4) * 4, '=')

export const decodeJwtPayload = <T extends Record<string, unknown>>(token: string): T | null => {
  const [, payload] = token.split('.')
  if (!payload) return null

  try {
    const decoded = atob(toBase64(payload))
    return JSON.parse(decoded) as T
  } catch {
    return null
  }
}
