// packages/skill-shared/src/auth/cookie-cache.ts
import { readFileSync, writeFileSync, mkdirSync, existsSync, unlinkSync } from 'node:fs';
import { join } from 'node:path';
import { getConfigDir } from '../config.js';
import { COOKIE_TTL_MS } from './constants.js';
const getCachePath = () => join(getConfigDir(), 'credentials.json');
export function readCookie() {
    const path = getCachePath();
    if (!existsSync(path))
        return null;
    const cache = JSON.parse(readFileSync(path, 'utf8'));
    const age = Date.now() - new Date(cache.cookieSavedAt).getTime();
    if (age > COOKIE_TTL_MS)
        return null;
    return cache.cookie;
}
export function readUserInfo() {
    const path = getCachePath();
    if (!existsSync(path))
        return null;
    const cache = JSON.parse(readFileSync(path, 'utf8'));
    const age = Date.now() - new Date(cache.cookieSavedAt).getTime();
    if (age > COOKIE_TTL_MS)
        return null;
    return cache.userInfo ?? null;
}
export function writeCookieAndUserInfo(cookie, userInfo) {
    mkdirSync(getConfigDir(), { recursive: true });
    const cache = {
        cookie,
        cookieSavedAt: new Date().toISOString(),
        userInfo,
    };
    writeFileSync(getCachePath(), JSON.stringify(cache, null, 2), 'utf8');
}
export function clearCookie() {
    const path = getCachePath();
    if (existsSync(path))
        unlinkSync(path);
}
export function readCacheTimestamp() {
    const path = getCachePath();
    if (!existsSync(path))
        return null;
    const cache = JSON.parse(readFileSync(path, 'utf8'));
    return cache.cookieSavedAt ?? null;
}
//# sourceMappingURL=cookie-cache.js.map