/**
 * Decode Firebase ID token payload (no signature verification — CLI only needs `sub`).
 * @param {string} token
 * @returns {string|null} Firebase uid (`sub`, or legacy `user_id`)
 */
function firebaseUidFromIdToken(token) {
  if (!token || typeof token !== 'string') return null
  const t = token.trim()
  const parts = t.split('.')
  if (parts.length < 2) return null
  try {
    const payloadJson = Buffer.from(parts[1], 'base64url').toString('utf8')
    const payload = JSON.parse(payloadJson)
    if (payload && typeof payload.sub === 'string' && payload.sub.length > 0) return payload.sub
    if (payload && typeof payload.user_id === 'string' && payload.user_id.length > 0) return payload.user_id
    return null
  } catch {
    return null
  }
}

module.exports = {
  firebaseUidFromIdToken,
}
