// @ts-nocheck
import * as q from './quark-api';

/**
 * 认证模块 — Cookie 验证、账号信息获取、QR 登录状态检查。
 * 所有方法以 cookie 字符串为参数，不持有驱动状态。
 * 依赖 quark-api.ts 统一端点模块 — URL 不再硬编码。
 */
// ==================== Validate ====================
/**
 * Validate the cookie by fetching user info.
 */
export async function validate(cookie) {
    const MAX_RETRIES = 2;
    for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
        try {
            const url = q.QUARK_PAN_HOST + q.EP.ACCOUNT_INFO + '?fr=pc&platform=pc';
            const response = await fetch(url, {
                headers: {
                    ...q.getHeaders(cookie),
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) quark-cloud-drive/3.14.2 Chrome/112.0.5615.165 Electron/24.1.3.8 Safari/537.36 Channel/pckk_other_ch',
                },
                signal: AbortSignal.timeout(15000),
            });
            if (!response.ok)
                return false;
            const data = await response.json();
            if (data?.data?.nickname)
                return true;
        }
        catch (err) {
            if (attempt < MAX_RETRIES) {
                console.log('[Quark] validate attempt ' + (attempt + 1) + ' failed: ' + err.message + ', retrying...');
                await new Promise(r => setTimeout(r, 2000));
                continue;
            }
            console.log('[Quark] validate all ' + (MAX_RETRIES + 1) + ' attempts failed: ' + err.message);
        }
    }
    return false;
}
/** Fetch nickname from Quark account info (same API used by quark-auto-save) */
export async function fetchNickname(cookie) {
    try {
        const url = q.QUARK_PAN_HOST + q.EP.ACCOUNT_INFO + '?fr=pc&platform=pc';
        const response = await fetch(url, {
            headers: {
                ...q.getHeaders(cookie),
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) quark-cloud-drive/3.14.2 Chrome/112.0.5615.165 Electron/24.1.3.8 Safari/537.36 Channel/pckk_other_ch',
            },
            signal: AbortSignal.timeout(15000),
        });
        if (!response.ok)
            return null;
        const data = await response.json();
        return data?.data?.nickname || null;
    }
    catch {
        return null;
    }
}
