////
// Session storage. 1 browser tab = 1 session

import { AsyncLocalStorage } from "async_hooks"

export type Session = {
    taskId?: string
    sessionId?: string
    project?: string
    cwd?: string
    ws?: any
}

// Ensure "ALS" lives between bun's hot reloads
const g = globalThis as typeof globalThis & { __thread?: AsyncLocalStorage<Session> }
export const ALS = g.__thread ??= new AsyncLocalStorage<Session>()

export function sessionGet(key?: keyof Session): Session | any | undefined {
    const store = ALS.getStore()
    if (!store) return

    if (key) return store[key]

    return store
}

export function sessionSet(key: keyof Session, value: any) {
    const store = ALS.getStore()
    if (!store) return
    store[key] = value
}