import { nanoid } from "nanoid"
import { useMemo } from "react"

export const SESSION_ID_KEY_NAME = "web_sessionId"

export function useSessionId(): string | null {
  const sessionId = useMemo(() => {
    if (typeof window === "undefined") {
      // Return null if running on the server
      return null
    }

    let currentSessionId = sessionStorage.getItem(SESSION_ID_KEY_NAME)
    if (!currentSessionId) {
      currentSessionId = nanoid()
      sessionStorage.setItem(SESSION_ID_KEY_NAME, currentSessionId)
    }
    return currentSessionId
  }, [])

  return sessionId
}
