// 记录推广链接访问
async function recordPromotionVisit(shortUrl) {
    try {
        const { data, error } = await useApiFetch(`/admin/promotion/link/record/${shortUrl}`)
            .get()
            .json();

        if (error.value) {
            throw new Error(error.value);
        }

        return data.value;
    } catch (error) {
        console.error("记录推广访问失败:", error);
        throw error;
    }
}

// 处理会话存储
function handleSessionStorage(promoteKey) {
    if (!promoteKey) return;

    try {
        // 存储推广key
        sessionStorage.setItem('promote_key', promoteKey);
        // 存储时间戳，用于判断会话是否过期
        sessionStorage.setItem('promote_timestamp', Date.now().toString());
    } catch (error) {
        console.error("存储会话信息失败:", error);
        throw error;
    }
}

// 统一的入口函数
export function handlePromotionLink(shortUrl) {
    // 使用 Promise.resolve().then 确保异步执行
    Promise.resolve().then(async () => {
        try {
            const response = await recordPromotionVisit(shortUrl);
            console.log(response);
            if (response.code === 200 && response.data.success) {
                handleSessionStorage(shortUrl);
            }
        } catch (error) {
            // 错误已经在各自的函数中处理，这里只做日志记录
            console.error("推广链接处理失败:", error);
        }
    });
}

// 获取会话数据
export function getPromotionSession() {
    try {
        const promoteKey = sessionStorage.getItem('promote_key');
        const timestamp = sessionStorage.getItem('promote_timestamp');

        // 检查会话是否过期（30天过期）
        const THIRTY_DAYS = 30 * 24 * 60 * 60 * 1000;
        if (timestamp && Date.now() - parseInt(timestamp) > THIRTY_DAYS) {
            clearPromotionSession();
            return null;
        }

        return promoteKey;
    } catch (error) {
        console.error("获取会话信息失败:", error);
        return null;
    }
}

// 清除会话数据
export function clearPromotionSession() {
    try {
        sessionStorage.removeItem('promote_key');
        sessionStorage.removeItem('promote_timestamp');
    } catch (error) {
        console.error("清除会话信息失败:", error);
    }
} 