/**
 * Outlook Graph subscription webhook helpers — calendar-module security (S7-003).
 */
import { timingSafeEqual } from '@zync/auth'

export const OUTLOOK_CLIENT_STATE_KV_PREFIX = 'outlook_client_state:'

export function outlookClientStateKey(connId: string): string {
  return `${OUTLOOK_CLIENT_STATE_KV_PREFIX}${connId}`
}

export interface OutlookNotification {
  clientState?: string
}

/** Parse MS Graph change-notification envelope; returns null when body is not valid JSON. */
export function parseOutlookNotifications(rawBody: string): OutlookNotification[] | null {
  if (!rawBody) return []
  try {
    const parsed = JSON.parse(rawBody) as { value?: OutlookNotification[] }
    return parsed.value ?? []
  } catch {
    return null
  }
}

/**
 * Fail closed unless every notification carries the stored per-subscription clientState.
 */
export function outlookNotificationsAuthorized(
  notifications: OutlookNotification[],
  storedClientState: string | null,
): boolean {
  if (!storedClientState) return false
  if (notifications.length === 0) return false
  return notifications.every(
    (n) => n.clientState && timingSafeEqual(n.clientState, storedClientState),
  )
}
