import { after } from 'next/server'
import { NextRequest, NextResponse } from 'next/server'
import { getTelegramConfig } from '@/lib/telegram-config'
import { sendTelegramText } from '@/lib/telegram-bot-api'
import { tryHandleHireTelegramCallback } from '@/lib/telegram-hire-callback'
import { formatUnauthorizedChat, TELEGRAM_HELP_TEXT } from '@/lib/telegram-messages'
import type { TelegramUpdate } from '@/lib/telegram-update-handler'

export const runtime = 'nodejs'
/** EU-near Telegram + US fallback — cuts cold-start hop latency */
export const preferredRegion = ['fra1', 'iad1']
export const dynamic = 'force-dynamic'

const WEBHOOK_VERSION = 'channel-cmd-4-hire'

function normId(id: string) {
  return id.replace(/^-100/, '-').replace(/^-/, '')
}

function isAllowedChat(chatId: string | number): boolean {
  const config = getTelegramConfig()
  if (!config) return false
  const chat = String(chatId).trim()
  if (chat === config.chatId.trim()) return true
  return Boolean(normId(chat) && normId(chat) === normId(config.chatId.trim()))
}

function extractCommand(update: TelegramUpdate): {
  chatId: number
  text: string
  source: string
} | null {
  const msg =
    update.channel_post || update.edited_channel_post || update.message
  if (!msg?.text) return null
  const text = msg.text.trim()
  if (!text.startsWith('/')) return null
  return { chatId: msg.chat.id, text, source: update.channel_post ? 'channel_post' : update.edited_channel_post ? 'edited_channel_post' : 'message' }
}

function baseCmd(text: string) {
  return text.split(/\s/)[0]?.split('@')[0]?.toLowerCase() || ''
}

/**
 * ACK Telegram immediately; run reply in `after()` so serverless stays alive.
 * /help and /start use a fast path (no Supabase import).
 */
export async function POST(request: NextRequest) {
  try {
    const update = (await request.json()) as TelegramUpdate

    // Hire buttons: answer synchronously (Telegram timeout + production must run latest code)
    if (update.callback_query?.data && update.callback_query.message) {
      const hireHandled = await tryHandleHireTelegramCallback(update.callback_query)
      if (hireHandled) {
        return NextResponse.json({
          ok: true,
          v: WEBHOOK_VERSION,
          handled: 'hire-callback',
        })
      }
    }

    const extracted = extractCommand(update)
    const cmd = extracted ? baseCmd(extracted.text) : ''

    // Fast path — no heavy panel/supabase module
    if (extracted && (cmd === '/help' || cmd === '/start')) {
      if (!isAllowedChat(extracted.chatId)) {
        after(async () => {
          await sendTelegramText(formatUnauthorizedChat(), {
            chatId: String(extracted.chatId),
            parseMode: 'HTML',
          })
        })
        return NextResponse.json({
          ok: true,
          v: WEBHOOK_VERSION,
          handled: 'none',
          source: extracted.source,
        })
      }

      const sendPromise = sendTelegramText(TELEGRAM_HELP_TEXT, {
        chatId: String(extracted.chatId),
        parseMode: 'HTML',
      })
      after(async () => {
        await sendPromise
      })

      return NextResponse.json({
        ok: true,
        v: WEBHOOK_VERSION,
        handled: 'command',
        source: extracted.source,
        chatId: String(extracted.chatId),
        command: cmd,
        fast: true,
      })
    }

    // Callbacks + /sessions + other commands
    after(async () => {
      const { processTelegramUpdate } = await import(
        '@/lib/telegram-update-handler'
      )
      await processTelegramUpdate(update)
    })

    return NextResponse.json({
      ok: true,
      v: WEBHOOK_VERSION,
      deferred: true,
    })
  } catch (error) {
    console.error('[telegram/webhook]', error)
    return NextResponse.json(
      {
        ok: false,
        v: WEBHOOK_VERSION,
        error: error instanceof Error ? error.message : 'webhook error',
      },
      { status: 500 }
    )
  }
}

/** Keep-warm + capability check */
export async function GET() {
  return NextResponse.json({
    ok: true,
    v: WEBHOOK_VERSION,
    hireCallbacks: ['hy1', 'hy0', 'hyr'],
    supports: ['message', 'channel_post', 'edited_channel_post', 'callback_query'],
    hint: 'Post /help as a channel admin. Bot must be channel admin.',
  })
}
