/**
 * WAHA (WhatsApp HTTP API) integration
 * Connects to waha.quikcue.com for sending WhatsApp messages
 *
 * WAHA runs as a Docker service in the same Swarm overlay network.
 * From within the pnpl container, we reach it via the published port or service DNS.
 */

const WAHA_URL = process.env.WAHA_API_URL || "http://tasks.qc-comms_waha:3000"
const WAHA_KEY = process.env.WAHA_API_KEY || "qc-waha-api-7Fp3nR9xYm2K"
const WAHA_SESSION = process.env.WAHA_SESSION || "default"

interface WahaResponse {
  id?: string
  error?: string
  message?: string
}

async function wahaFetch(path: string, body?: Record<string, unknown>): Promise<WahaResponse> {
  try {
    const res = await fetch(`${WAHA_URL}${path}`, {
      method: body ? "POST" : "GET",
      headers: {
        "Content-Type": "application/json",
        "X-Api-Key": WAHA_KEY,
      },
      ...(body ? { body: JSON.stringify(body) } : {}),
      signal: AbortSignal.timeout(10000),
    })
    return res.json()
  } catch (err) {
    console.error("[WAHA]", path, err)
    return { error: String(err) }
  }
}

/**
 * Normalize UK phone to WhatsApp JID format
 * 07700900000 → 447700900000@c.us
 * +447700900000 → 447700900000@c.us
 */
function toJid(phone: string): string {
  let clean = phone.replace(/[\s\-\(\)]/g, "")
  if (clean.startsWith("+")) clean = clean.slice(1)
  if (clean.startsWith("0")) clean = "44" + clean.slice(1) // UK
  if (!clean.includes("@")) clean += "@c.us"
  return clean
}

/**
 * Check if WAHA session is connected and ready
 */
export async function isWhatsAppReady(): Promise<boolean> {
  try {
    const sessions = await wahaFetch("/api/sessions")
    if (Array.isArray(sessions)) {
      return sessions.some((s: { name: string; status: string }) =>
        s.name === WAHA_SESSION && s.status === "WORKING"
      )
    }
    return false
  } catch {
    return false
  }
}

/**
 * Send a text message via WhatsApp
 */
export async function sendWhatsAppMessage(
  phone: string,
  text: string
): Promise<{ success: boolean; messageId?: string; error?: string }> {
  const jid = toJid(phone)
  const result = await wahaFetch(`/api/sendText`, {
    session: WAHA_SESSION,
    chatId: jid,
    text,
  })

  if (result.id) {
    return { success: true, messageId: result.id }
  }
  return { success: false, error: result.error || result.message || "Unknown error" }
}

/**
 * Send pledge receipt via WhatsApp
 */
export async function sendPledgeReceipt(phone: string, data: {
  donorName?: string
  amountPounds: string
  eventName: string
  reference: string
  rail: string
  bankDetails?: { sortCode: string; accountNo: string; accountName: string }
  orgName?: string
}): Promise<{ success: boolean; error?: string }> {
  const name = data.donorName?.split(" ")[0] || "there"
  const railEmoji: Record<string, string> = { bank: "🏦", card: "💳", gocardless: "🏛️" }
  const railLabel: Record<string, string> = { bank: "Bank Transfer", card: "Card", gocardless: "Direct Debit" }

  let msg = `🤲 *Pledge Confirmed!*\n\n`
  msg += `Thank you, ${name}!\n\n`
  msg += `💷 *£${data.amountPounds}* pledged to *${data.eventName}*\n`
  msg += `${railEmoji[data.rail] || "💰"} Via: ${railLabel[data.rail] || data.rail}\n`
  msg += `🔖 Ref: \`${data.reference}\`\n`

  if (data.rail === "bank" && data.bankDetails) {
    msg += `\n━━━━━━━━━━━━━━━━━━\n`
    msg += `*Transfer to:*\n`
    msg += `Sort Code: \`${data.bankDetails.sortCode}\`\n`
    msg += `Account: \`${data.bankDetails.accountNo}\`\n`
    msg += `Name: ${data.bankDetails.accountName}\n`
    msg += `Reference: \`${data.reference}\`\n`
    msg += `━━━━━━━━━━━━━━━━━━\n`
    msg += `\n⚠️ _Use the exact reference above_\n`
  }

  if (data.rail === "gocardless") {
    msg += `\n✅ Direct Debit will be collected in 3-5 working days.\n`
    msg += `Protected by the Direct Debit Guarantee.\n`
  }

  if (data.rail === "card") {
    msg += `\n✅ Payment processed — receipt sent to your email.\n`
  }

  msg += `\n_${data.orgName || "Powered by Pledge Now, Pay Later"}_`

  return sendWhatsAppMessage(phone, msg)
}

/**
 * Send a payment reminder via WhatsApp
 */
export async function sendPledgeReminder(phone: string, data: {
  donorName?: string
  amountPounds: string
  eventName: string
  reference: string
  daysSincePledge: number
  step: number // 0=gentle, 1=nudge, 2=urgent, 3=final
}): Promise<{ success: boolean; error?: string }> {
  const name = data.donorName?.split(" ")[0] || "there"

  const templates = [
    // Step 0: Gentle
    `Hi ${name} 👋\n\nJust a quick reminder about your *£${data.amountPounds}* pledge to ${data.eventName}.\n\nIf you've already paid — thank you! 🙏\nIf not, your ref is: \`${data.reference}\`\n\nReply *PAID* if you've sent it, or *HELP* if you need the bank details again.`,
    // Step 1: Nudge
    `Hi ${name},\n\nYour *£${data.amountPounds}* pledge to ${data.eventName} is still pending (${data.daysSincePledge} days).\n\nEvery pound makes a real difference. 🤲\n\nRef: \`${data.reference}\`\n\nReply *PAID* once transferred, or *CANCEL* to withdraw.`,
    // Step 2: Urgent
    `Hi ${name},\n\nWe're reaching out about your *£${data.amountPounds}* pledge from ${data.eventName}.\n\nIt's been ${data.daysSincePledge} days and we haven't received the payment yet.\n\nRef: \`${data.reference}\`\n\nReply *PAID*, *HELP*, or *CANCEL*.`,
    // Step 3: Final
    `Hi ${name},\n\nThis is our final message about your *£${data.amountPounds}* pledge to ${data.eventName}.\n\nWe completely understand if circumstances have changed. Reply:\n\n*PAID* — if you've sent it\n*CANCEL* — to withdraw the pledge\n*HELP* — to get bank details\n\nRef: \`${data.reference}\``,
  ]

  const text = templates[Math.min(data.step, 3)]
  return sendWhatsAppMessage(phone, text)
}

/**
 * Notify volunteer when someone pledges at their table/QR
 */
export async function notifyVolunteer(phone: string, data: {
  volunteerName: string
  donorName?: string
  amountPounds: string
  eventName: string
  totalPledges: number
  totalAmount: string
}): Promise<{ success: boolean; error?: string }> {
  let msg = `🎉 *New Pledge!*\n\n`
  msg += `${data.donorName || "Someone"} just pledged *£${data.amountPounds}* at your table!\n\n`
  msg += `📊 Your total: *${data.totalPledges} pledges* · *£${data.totalAmount}*\n`
  msg += `\nKeep going, ${data.volunteerName}! 💪`

  return sendWhatsAppMessage(phone, msg)
}

/**
 * Check WAHA status for health checks
 */
export async function getWhatsAppStatus(): Promise<{
  connected: boolean
  session: string
  version?: string
}> {
  try {
    const ready = await isWhatsAppReady()
    const version = await wahaFetch("/api/version")
    return {
      connected: ready,
      session: WAHA_SESSION,
      version: (version as { version?: string }).version,
    }
  } catch {
    return { connected: false, session: WAHA_SESSION }
  }
}
