import axios from 'axios'

interface OrderData {
  phone: string
  productName: string
  productSlug: string
  timestamp: string
}

export async function sendTelegramMessage(data: OrderData): Promise<void> {
  const { TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID } = process.env

  if (!TELEGRAM_BOT_TOKEN || !TELEGRAM_CHAT_ID) {
    throw new Error('Telegram configuration is missing')
  }

  const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://modul-construction.com.ua'
  const productUrl = `${siteUrl}/products/${data.productSlug}/`

  const message = `
🔔 *Нова заявка на товар*

📦 *Товар:* ${data.productName}
📞 *Телефон:* ${data.phone}
🕐 *Час:* ${data.timestamp}

🔗 [Переглянути товар](${productUrl})

---
_Modul Construction_
  `.trim()

  const url = `https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage`

  try {
    await axios.post(url, {
      chat_id: TELEGRAM_CHAT_ID,
      text: message,
      parse_mode: 'Markdown',
      disable_web_page_preview: false,
    })
  } catch (error) {
    if (axios.isAxiosError(error)) {
      throw new Error(`Telegram API error: ${error.response?.data?.description || error.message}`)
    }
    throw error
  }
}

