import 'server-only'

// Outbound Telegram. One direction only — the bot speaking to a chat.
//
// Every send is best-effort and never throws: this carries notifications
// ABOUT work that already succeeded, so a Telegram hiccup must not turn a
// completed capture into a failed request.
const API = 'https://api.telegram.org'

function creds(): { token: string; chatId: string } | null {
  const token = process.env.TELEGRAM_BOT_TOKEN?.trim()
  const chatId = process.env.TELEGRAM_CHAT_ID?.trim()
  return token && chatId ? { token, chatId } : null
}

/**
 * Send a message to a chat. `chatId` overrides the default, for a household
 * member with their own chat.
 *
 * Markdown is deliberately NOT enabled: these messages carry user text —
 * list names, customer names, transcripts — and an unmatched asterisk in any
 * of it makes Telegram reject the whole message with a parse error. Plain
 * text always arrives.
 */
export async function sendTelegram(text: string, chatId?: string): Promise<boolean> {
  const c = creds()
  if (!c || !text.trim()) return false
  // Telegram's hard cap is 4096 characters; truncate rather than be refused.
  const body = text.length > 3900 ? `${text.slice(0, 3900)}\n… (truncated)` : text
  try {
    const res = await fetch(`${API}/bot${c.token}/sendMessage`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        chat_id: chatId || c.chatId,
        text: body,
        disable_web_page_preview: true,
      }),
      signal: AbortSignal.timeout(10_000),
    })
    if (!res.ok) console.error('[telegram] send failed:', res.status, await res.text().catch(() => ''))
    return res.ok
  } catch (e) {
    console.error('[telegram] send threw:', e)
    return false
  }
}
