import {
  renderOrderCreatedTg,
  renderOrderStatusChangedTg,
  renderOrderMessageTg,
  renderPaymentStatusChangedTg,
  renderAdminOrderCreatedTg,
  renderAdminNewReviewTg,
  renderAuthCodeTg,
  renderDeliveryFeeAdjustedTg,
} from '../templates/telegram-templates.js'

const TELEGRAM_BOT_TOKEN = process.env.TELEGRAM_BOT_TOKEN || ''

const templateRenderers = {
  'order:created': renderOrderCreatedTg,
  'order:statusChanged': renderOrderStatusChangedTg,
  'orderMessage:adminReply': renderOrderMessageTg,
  'payment:statusChanged': renderPaymentStatusChangedTg,
  'order:created:admin': renderAdminOrderCreatedTg,
  'orderMessage:sent': renderOrderMessageTg,
  'review:created': renderAdminNewReviewTg,
  'auth:codeRequested': renderAuthCodeTg,
  'order:deliveryFeeAdjusted': renderDeliveryFeeAdjustedTg,
}

async function postToTelegram(chatId, text) {
  if (!TELEGRAM_BOT_TOKEN) {
    console.info(`[DEV] telegram to ${chatId}: ${text.slice(0, 80)}`)
    return { success: true }
  }

  try {
    const res = await fetch(`https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        chat_id: chatId,
        text,
        parse_mode: 'HTML',
      }),
    })

    const data = await res.json()
    if (!data.ok) {
      return { success: false, error: data.description || 'Telegram API error' }
    }
    return { success: true }
  } catch (err) {
    return { success: false, error: err.message }
  }
}

export const telegramChannel = {
  name: 'telegram',

  async send({ recipient: chatId, eventType, payload }) {
    if (!chatId) {
      return { success: false, error: 'No telegram chatId' }
    }

    const renderer = templateRenderers[eventType]
    if (!renderer) {
      return { success: false, error: `No telegram template for event: ${eventType}` }
    }

    const text = renderer(payload)
    return postToTelegram(chatId, text)
  },
}
