import Cookies from 'js-cookie';
import { v4 as uuidv4 } from 'uuid';
import { getBaseDomain } from './utils/get-base-domain.js';
const CORRELATION_ID_KEY = 'CORRELATION_ID';
const SESSION_ID_KEY = 'SESSION_ID';
function getRuntimeAPIsSafely() {
    return {
        safeSessionStorage: 'sessionStorage' in globalThis ? sessionStorage : null,
        safeUrl: 'document' in globalThis ? document.location.href : null
    };
}
/**
 * Gets correlation ID from cookies.
 * If one does not exist yet, one will be generated.
 */
export function getCorrelationId() {
    const { safeUrl } = getRuntimeAPIsSafely();
    const existingValue = Cookies.get(CORRELATION_ID_KEY);
    if (existingValue)
        return existingValue;
    const domain = safeUrl ? getBaseDomain(safeUrl) : null;
    const newValue = uuidv4();
    Cookies.set(CORRELATION_ID_KEY, newValue, {
        domain: domain !== null && domain !== void 0 ? domain : undefined,
        expires: 999999
    });
    return newValue;
}
/**
 * Gets session ID from sessionStorage.
 * If one does not exist yet, one will be generated.
 */
export function getSessionId() {
    const { safeSessionStorage } = getRuntimeAPIsSafely();
    if (!safeSessionStorage)
        return undefined;
    const existingValue = safeSessionStorage.getItem(SESSION_ID_KEY);
    if (existingValue)
        return existingValue;
    const newValue = uuidv4();
    safeSessionStorage.setItem(SESSION_ID_KEY, newValue);
    return newValue;
}
