import { getTelegramConfig } from '@/lib/telegram-config'

export type InlineKeyboardButton = {
  text: string
  callback_data: string
}

export type TelegramApiResult<T = unknown> = {
  ok: boolean
  result?: T
  description?: string
}

export async function telegramApi<T = unknown>(
  method: string,
  body: Record<string, unknown>
): Promise<TelegramApiResult<T>> {
  const config = getTelegramConfig()
  if (!config) {
    return { ok: false, description: 'Telegram not configured' }
  }

  try {
    const response = await fetch(`${config.apiUrl}/${method}`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body),
    })
    const data = (await response.json()) as TelegramApiResult<T>
    if (!data.ok) {
      console.error(`[telegram] ${method} failed:`, data.description)
    }
    return data
  } catch (error) {
    console.error(`[telegram] ${method} error:`, error)
    return {
      ok: false,
      description: error instanceof Error ? error.message : 'Network error',
    }
  }
}

export async function sendTelegramText(
  text: string,
  options?: {
    chatId?: string
    replyMarkup?: { inline_keyboard: InlineKeyboardButton[][] }
    parseMode?: 'HTML' | 'Markdown'
  }
): Promise<boolean> {
  const config = getTelegramConfig()
  if (!config) return false

  try {
    const response = await fetch(`${config.apiUrl}/sendMessage`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        chat_id: options?.chatId ?? config.chatId,
        text,
        disable_web_page_preview: true,
        ...(options?.parseMode ? { parse_mode: options.parseMode } : {}),
        ...(options?.replyMarkup ? { reply_markup: options.replyMarkup } : {}),
      }),
    })
    const data = (await response.json()) as TelegramApiResult
    if (!data.ok) {
      console.error('[telegram] sendMessage failed:', data.description)
    }
    return Boolean(data.ok)
  } catch (error) {
    console.error('[telegram] sendMessage error:', error)
    return false
  }
}

export async function answerCallbackQuery(
  callbackQueryId: string,
  text?: string
): Promise<void> {
  await telegramApi('answerCallbackQuery', {
    callback_query_id: callbackQueryId,
    text,
    show_alert: Boolean(text && text.length > 40),
  })
}

export async function editMessageText(
  chatId: string | number,
  messageId: number,
  text: string,
  replyMarkup?: { inline_keyboard: InlineKeyboardButton[][] },
  parseMode?: 'HTML' | 'Markdown'
): Promise<boolean> {
  const result = await telegramApi('editMessageText', {
    chat_id: chatId,
    message_id: messageId,
    text,
    disable_web_page_preview: true,
    ...(parseMode ? { parse_mode: parseMode } : {}),
    ...(replyMarkup ? { reply_markup: replyMarkup } : {}),
  })
  return result.ok
}

export async function getTelegramWebhookInfo(): Promise<
  TelegramApiResult<{
    url?: string
    pending_update_count?: number
    allowed_updates?: string[]
    last_error_message?: string
    last_error_date?: number
  }>
> {
  return telegramApi('getWebhookInfo', {})
}

export async function setTelegramWebhook(
  webhookUrl: string,
  options?: { dropPendingUpdates?: boolean }
): Promise<TelegramApiResult> {
  return telegramApi('setWebhook', {
    url: webhookUrl,
    allowed_updates: ['message', 'channel_post', 'edited_channel_post', 'callback_query'],
    ...(options?.dropPendingUpdates ? { drop_pending_updates: true } : {}),
  })
}
