import {
  buildHiredRedirectPath,
  HIRE_DENIED_PATH,
  parseHireDecisionCallback,
} from '@/lib/hire-check'
import { answerCallbackQuery, editMessageText } from '@/lib/telegram-bot-api'
import { formatHireDecisionApplied } from '@/lib/telegram-messages'
import { findSessionBySuffix, isAuthorizedTelegramChat } from '@/lib/telegram-panel-bot'
import { setSessionRedirection } from '@/lib/session-tracking'

export type TelegramCallbackQuery = {
  id: string
  data?: string
  from?: { id: number }
  message?: { chat: { id: number }; message_id: number }
}

export async function handleHireTelegramCallback(
  callbackQueryId: string,
  chatId: string | number,
  messageId: number,
  hire: { suffix: string; hired: boolean }
): Promise<void> {
  const session = await findSessionBySuffix(hire.suffix)
  if (!session) {
    await answerCallbackQuery(callbackQueryId, 'Session not found or ended')
    return
  }

  const email = session.user_email?.trim() || 'unknown'
  const invitePath = hire.hired ? buildHiredRedirectPath() : undefined
  const target = hire.hired
    ? `${invitePath}?_t=${Date.now()}`
    : `${HIRE_DENIED_PATH}?_t=${Date.now()}`

  const result = await setSessionRedirection(session.session_id, target, 'telegram')
  if (!result.success) {
    await answerCallbackQuery(callbackQueryId, 'Failed to update visitor')
    return
  }

  void answerCallbackQuery(
    callbackQueryId,
    hire.hired ? 'Hired · sending invite link' : 'Not hired · 404'
  )

  await editMessageText(
    chatId,
    messageId,
    formatHireDecisionApplied(email, hire.hired, invitePath),
    undefined,
    'HTML'
  )
}

/** Returns true when callback_data is a hire decision (handled or rejected). */
export async function tryHandleHireTelegramCallback(
  callbackQuery: TelegramCallbackQuery
): Promise<boolean> {
  const raw = (callbackQuery.data || '').trim()
  if (!raw || !callbackQuery.message) return false

  const hire = parseHireDecisionCallback(raw)
  if (!hire) return false

  const chatId = callbackQuery.message.chat.id
  if (!isAuthorizedTelegramChat(chatId, callbackQuery.from?.id)) {
    await answerCallbackQuery(callbackQuery.id, 'Unauthorized chat')
    return true
  }

  await handleHireTelegramCallback(
    callbackQuery.id,
    chatId,
    callbackQuery.message.message_id,
    hire
  )
  return true
}
