const TOKEN_KEY = 'teller_token';
const USER_DATA_KEY = 'teller_userData';

/** Matches backend jwt.token-validity-time (PT30M). */
const SESSION_MAX_AGE_SECONDS = 30 * 60;

function getCookie(name) {
    const prefix = `${encodeURIComponent(name)}=`;
    const parts = document.cookie ? document.cookie.split('; ') : [];

    for (const part of parts) {
        if (part.startsWith(prefix)) {
            return decodeURIComponent(part.slice(prefix.length));
        }
    }

    return null;
}

function setCookie(name, value, maxAgeSeconds = SESSION_MAX_AGE_SECONDS) {
    const secure = window.location.protocol === 'https:' ? '; Secure' : '';
    document.cookie = [
        `${encodeURIComponent(name)}=${encodeURIComponent(value)}`,
        'Path=/',
        `Max-Age=${maxAgeSeconds}`,
        'SameSite=Lax',
        secure,
    ].join('; ');
}

function removeCookie(name) {
    document.cookie = `${encodeURIComponent(name)}=; Path=/; Max-Age=0; SameSite=Lax`;
}

export function getToken() {
    return getCookie(TOKEN_KEY);
}

export function setToken(token) {
    if (token == null || token === '') {
        removeCookie(TOKEN_KEY);
        return;
    }
    setCookie(TOKEN_KEY, token);
}

export function getUserData() {
    const raw = getCookie(USER_DATA_KEY) ?? sessionStorage.getItem(USER_DATA_KEY);
    if (!raw) {
        return null;
    }

    try {
        return JSON.parse(raw);
    } catch {
        removeCookie(USER_DATA_KEY);
        sessionStorage.removeItem(USER_DATA_KEY);
        return null;
    }
}

export function setUserData(userData) {
    if (userData == null) {
        removeCookie(USER_DATA_KEY);
        sessionStorage.removeItem(USER_DATA_KEY);
        return;
    }

    const serialized = JSON.stringify(userData);
    setCookie(USER_DATA_KEY, serialized);
    sessionStorage.setItem(USER_DATA_KEY, serialized);
}

export function setSession({ token, userData } = {}) {
    if (token !== undefined) {
        setToken(token);
    }
    if (userData !== undefined) {
        setUserData(userData);
    }
}

export function clearSession() {
    removeCookie(TOKEN_KEY);
    removeCookie(USER_DATA_KEY);
    sessionStorage.removeItem(USER_DATA_KEY);
}
