"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.saveAuthorization = saveAuthorization;
exports.getAuthorization = getAuthorization;
exports.clearAuthorizationCache = clearAuthorizationCache;
exports.isAuthorizationInvalidError = isAuthorizationInvalidError;
const fs_extra_1 = __importDefault(require("fs-extra"));
const path_1 = __importDefault(require("path"));
const CACHE_DIR = path_1.default.join(require('os').homedir(), '.mid-cli');
const CACHE_FILE = path_1.default.join(CACHE_DIR, 'auth-cache.json');
/**
 * 保存 authorization 到缓存
 */
async function saveAuthorization(authorization) {
    await fs_extra_1.default.ensureDir(CACHE_DIR);
    const cacheData = {
        authorization,
        timestamp: Date.now()
    };
    await fs_extra_1.default.writeJson(CACHE_FILE, cacheData, { spaces: 2 });
}
/**
 * 从缓存中读取 authorization
 */
async function getAuthorization() {
    try {
        if (!await fs_extra_1.default.exists(CACHE_FILE)) {
            return null;
        }
        const cacheData = await fs_extra_1.default.readJson(CACHE_FILE);
        if (!cacheData?.authorization || typeof cacheData.authorization !== 'string') {
            return null;
        }
        return cacheData.authorization;
    }
    catch (error) {
        return null;
    }
}
/**
 * 清除 authorization 缓存
 */
async function clearAuthorizationCache() {
    try {
        if (await fs_extra_1.default.exists(CACHE_FILE)) {
            await fs_extra_1.default.remove(CACHE_FILE);
        }
    }
    catch (error) {
    }
}
function isAuthorizationInvalidError(error) {
    const message = String(error?.message || '').toLowerCase();
    const status = Number(error?.response?.status || 0);
    const code = String(error?.response?.data?.code || error?.code || '').toLowerCase();
    return status === 401
        || status === 403
        || code === '3000'
        || message.includes('未登录')
        || message.includes('未授权')
        || message.includes('授权')
        || message.includes('token')
        || message.includes('过期')
        || message.includes('forbidden')
        || message.includes('unauthorized')
        || message.includes('invalid token');
}
//# sourceMappingURL=cache.js.map