/**
 * `ai_telegram_message` queue consumer — ai-assistant.
 *
 * Processes inbound Telegram messages routed through the AI assistant flow.
 * Loads last-5 messages by telegram_chat_id, calls runAssistantTurn (non-streaming),
 * and replies via the tenant's Telegram bot token.
 *
 * Tier guard: below Business → no reply, ack message.
 */
import type { MessageBatch } from '@cloudflare/workers-types'
import type { Env } from '@zync/types'
import { createDb } from '@zync/db/queries'
import { getTenantById } from '@zync/db/queries'
import type { TenantId } from '@zync/types'
import { runAssistantTurn } from '@zync/ai/chat'
import { loadAdapterCredential } from '@zync/notifications'

export interface AiTelegramMessageJob {
  tenantId: string
  telegramChatId: string
  message: string
}

async function sendTelegramMessage(token: string, chatId: string, text: string): Promise<void> {
  const res = await fetch(`https://api.telegram.org/bot${token}/sendMessage`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ chat_id: chatId, text, parse_mode: 'HTML' }),
  })
  if (!res.ok) {
    const body = await res.text()
    throw new Error(`Telegram sendMessage failed: ${res.status} ${body}`)
  }
}

export async function handleAiTelegramMessage(
  batch: MessageBatch<AiTelegramMessageJob>,
  env: Env,
): Promise<void> {
  for (const msg of batch.messages) {
    const job = msg.body

    if (!job || !job.tenantId || !job.telegramChatId || !job.message) {
      console.warn('[ai-telegram] Malformed job, discarding:', job)
      msg.ack()
      continue
    }

    try {
      const db = createDb(env)
      const tenant = await getTenantById(db, job.tenantId as TenantId)

      if (!tenant) {
        console.warn('[ai-telegram] Tenant not found:', job.tenantId)
        msg.ack()
        continue
      }

      // Tier guard: Business+ required
      const tier = tenant.tier
      if (tier !== 'business' && tier !== 'enterprise' && tier !== 'white_label') {
        // Below Business — no AI reply, silently ack
        msg.ack()
        continue
      }

      // Run the assistant turn (non-streaming)
      const { reply } = await runAssistantTurn(env, {
        tenantId: job.tenantId,
        channel: 'telegram',
        message: job.message,
        telegramChatId: job.telegramChatId,
        tier,
      })

      // Load bot token and send reply
      const token = await loadAdapterCredential(
        db,
        job.tenantId,
        'telegram',
        env.INTEGRATION_ENCRYPTION_KEY,
      )

      if (!token) {
        console.warn('[ai-telegram] No Telegram bot token for tenant:', job.tenantId)
        msg.ack()
        continue
      }

      await sendTelegramMessage(token, job.telegramChatId, reply)
      msg.ack()
    } catch (err) {
      console.error('[ai-telegram] Transient failure, will retry:', err)
      msg.retry()
    }
  }
}
