/* Telegram bot proxy — 透過 Cloudflare Worker（worker/intraday-worker.js）
 *
 * window.Telegram = {
 *   getChatId() / setChatId(id)
 *   getMe()                → bot 資訊（驗證 token）
 *   listRecentChats()      → 最近聊過的 chat 清單（自動偵測 chat_id 用）
 *   sendMessage(text, opts?)
 *   isEnabled()            → bool（worker URL + chat_id 都設好）
 * }
 *
 * Bot token 不在前端，存於 Worker env.TELEGRAM_BOT_TOKEN。
 * Chat ID 存於 localStorage（每瀏覽器各自）。
 */

const CHAT_ID_KEY = "telegram.chatId";

function getChatId() {
  return (window.TWStorage && window.TWStorage.get(CHAT_ID_KEY)) || "";
}
function setChatId(id) {
  if (window.TWStorage) window.TWStorage.set(CHAT_ID_KEY, String(id || "").trim());
}

async function workerFetch(path, opts = {}) {
  const base = window.Intraday && window.Intraday.getWorkerUrl();
  if (!base) throw new Error("尚未設定 Worker URL（Settings → 即時報價）");
  const url = base.replace(/\/$/, "") + path;
  const headers = { ...(opts.headers || {}) };
  const auth = window.Intraday && window.Intraday.getAuth();
  if (auth) headers["X-Auth"] = auth;
  if (opts.body && !headers["Content-Type"]) headers["Content-Type"] = "application/json";
  const res = await fetch(url, { ...opts, headers });
  const text = await res.text();
  let json;
  try { json = JSON.parse(text); }
  catch (e) { throw new Error(`Worker 回傳非 JSON：${text.slice(0, 80)}`); }
  if (!res.ok || json.error) throw new Error(json.error || `HTTP ${res.status}`);
  return json;
}

async function getMe() {
  return workerFetch("/telegram/me");
}

async function listRecentChats() {
  const json = await workerFetch("/telegram/updates");
  return json.chats || [];
}

async function sendMessage(text, opts = {}) {
  const chatId = opts.chat_id || getChatId();
  if (!chatId) throw new Error("尚未設定 Chat ID");
  return workerFetch("/telegram/send", {
    method: "POST",
    body: JSON.stringify({
      chat_id: chatId,
      text,
      parse_mode: opts.parse_mode || "HTML",
      disable_notification: opts.silent || false,
    }),
  });
}

function isEnabled() {
  const base = window.Intraday && window.Intraday.getWorkerUrl();
  return !!base && !!getChatId();
}

window.Telegram = {
  getChatId, setChatId, getMe, listRecentChats, sendMessage, isEnabled,
};
