/**
 * 公共工具方法
 */

// 带超时的 fetch 封装
async function customFetch(url, options = {}, timeout = 60000) {
    try {
        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), timeout);
        console.log(url,options,fetch,'fetchfetchfetchfetch');
         
        const response = await fetch(url, {
            ...options,
            signal: controller.signal
        });
        
        clearTimeout(timeoutId);
        
        if (!response.ok) {
            console.error(`HTTP error! status: ${response.status}`);
            return;
        }
       
          // 核心：自动判断响应格式
    const contentType = response.headers.get("Content-Type");
     
    if (contentType?.includes("application/json")) {
      // JSON 格式：解析为对象
      return await response.json();
    } else {
      // 非 JSON 格式：按文本读取（适配 text/plain、text/html 等）
      return await response.text();
    }
    } catch (error) {
        console.error('Fetch request failed:', error);
        return;
    }
}

// 从 chrome.storage.local 获取数据
async function getStorageValue(keys) {
    return new Promise((resolve, reject) => {
        if(keys === 'accessToken'){
       // 兼容 token 获取
         chrome.storage.sync.get(['token'], (result) => {
            if (chrome.runtime.lastError) {
                reject(chrome.runtime.lastError);
            } else {
                resolve(result);
            }
        });
        }else if(keys === 'messageEmail'){
         chrome.storage.sync.get(['messageEmail'], (result) => {
            if (chrome.runtime.lastError) {
                reject(chrome.runtime.lastError);
            } else {
                resolve(result);
            }
        });
        }else{
           chrome.storage.local.get(keys, (result) => {
            if (chrome.runtime.lastError) {
                reject(chrome.runtime.lastError);
            } else {
                resolve(result);
            }
        });
        }

     
    });
}

// 保存数据到 chrome.storage.local
async function setStorageValue(key, value) {
    return new Promise((resolve, reject) => {
        chrome.storage.local.set({ [key]: value }, () => {
            if (chrome.runtime.lastError) {
                reject(chrome.runtime.lastError);
            } else {
                resolve(true);
            }
        });
    });
}

// 获取 cookies 的封装
async function getCookies() {
    return new Promise((resolve, reject) => {
        chrome.runtime.sendMessage({ type: "getCookies" }, response => {
            if (chrome.runtime.lastError) {
                reject(chrome.runtime.lastError);
            } else {
                resolve(response);
            }
        });
    });
}

// 获取特定 cookie 值
async function getCookieValue(name) {
    return new Promise((resolve, reject) => {
        chrome.runtime.sendMessage(
            { action: 'getCookie', name: name },
            (response) => {
                if (response.error) reject(response.error);
                else resolve(response.value);
            }
        );
    });
}

async function getAllCookies() {
    return new Promise((resolve, reject) => {
        chrome.runtime.sendMessage(
            { action: 'getAllCookies' },
            (response) => {
                if (response.error) reject(response.error);
                else resolve(response.cookies);
            }
        );
    });
}
