// Server-only voice SMS: Africa's Talking client, voice sends and call
// callbacks. Credentials come from /admin/settings, falling back to
// environment variables, like the Moolre settings.
import { and, eq, inArray, like, sql } from 'drizzle-orm'
import { z } from 'zod'
import { db } from '../../db/index.js'
import { appSettings, campaigns, voiceCalls } from '../../db/schema.js'
import { refundCredits, spendCredits } from './billing.server'
import { SendError } from './messaging.server'
import { MAX_VOICE_CHARS, MAX_VOICE_RECIPIENTS, VOICE_CREDITS_PER_RECIPIENT, VOICE_FIELDS, type Voice, type VoiceFieldKey } from './voice'

const SETTING_PREFIX = 'voice.'
const CACHE_MS = 30_000
const BATCH_SIZE = 100

export type VoiceConfig = Record<VoiceFieldKey, string>

let cached: { at: number; values: Map<string, string> } | null = null

async function savedRows() {
  return db.select().from(appSettings).where(like(appSettings.key, `${SETTING_PREFIX}%`))
}

export async function getVoiceConfig(): Promise<VoiceConfig> {
  if (!cached || Date.now() - cached.at >= CACHE_MS) {
    const rows = await savedRows()
    cached = { at: Date.now(), values: new Map(rows.map((r) => [r.key.slice(SETTING_PREFIX.length), r.value])) }
  }
  const config = {} as VoiceConfig
  for (const field of VOICE_FIELDS) config[field.key] = (cached.values.get(field.key) || process.env[field.env] || '').trim()
  return config
}

export async function isVoiceConfigured() {
  const config = await getVoiceConfig()
  return VOICE_FIELDS.every((f) => Boolean(config[f.key]))
}

// Where each value currently comes from, for the settings page. Always reads fresh.
export async function getVoiceConfigSources() {
  const rows = await savedRows()
  return {
    saved: new Map(rows.map((r) => [r.key.slice(SETTING_PREFIX.length), r])),
    envSet: Object.fromEntries(VOICE_FIELDS.map((f) => [f.key, Boolean(process.env[f.env])])) as Record<VoiceFieldKey, boolean>,
  }
}

export async function saveVoiceSettings(changes: Record<string, string | null>, updatedBy: string) {
  for (const [key, value] of Object.entries(changes)) {
    const dbKey = `${SETTING_PREFIX}${key}`
    if (value === null) {
      await db.delete(appSettings).where(eq(appSettings.key, dbKey))
    } else {
      await db
        .insert(appSettings)
        .values({ key: dbKey, value, updatedBy })
        .onConflictDoUpdate({ target: appSettings.key, set: { value, updatedBy, updatedAt: new Date() } })
    }
  }
  cached = null
}

// The "sandbox" username always talks to the sandbox API.
function voiceUrl(config: VoiceConfig) {
  return config.username === 'sandbox' ? 'https://voice.sandbox.africastalking.com' : 'https://voice.africastalking.com'
}

const callResponse = z.object({
  entries: z
    .array(
      z.object({
        phoneNumber: z.string(),
        status: z.string(),
        sessionId: z.string().nullish(),
      }),
    )
    .nullish(),
  errorMessage: z.string().nullish(),
})

// Asks Africa's Talking to call each number. Calls are queued on their side
// and placed one after another from the voice number.
async function placeCalls(config: VoiceConfig, to: string[], clientRequestId: string) {
  let res: Response
  try {
    res = await fetch(`${voiceUrl(config)}/call`, {
      method: 'POST',
      headers: { apiKey: config.apiKey, Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' },
      body: new URLSearchParams({ username: config.username, from: config.phoneNumber, to: to.join(','), clientRequestId }),
      signal: AbortSignal.timeout(20_000),
    })
  } catch (error) {
    console.error("Africa's Talking call request failed", error)
    throw new Error('We could not reach the voice service. Please try again in a moment.', { cause: error })
  }
  const text = await res.text()
  let json: unknown = null
  try {
    json = JSON.parse(text)
  } catch {
    // Errors such as a bad API key come back as plain text.
  }
  const parsed = callResponse.safeParse(json)
  if (!res.ok || !parsed.success) {
    console.error("Africa's Talking call failed", res.status, text.slice(0, 300))
    const reason =
      res.status === 401 || /auth|api ?key/i.test(text) ? 'The voice service rejected our credentials.' : 'The voice service could not place these calls.'
    return { ok: false as const, reason, authFailed: res.status === 401 }
  }
  const error = parsed.data.errorMessage && parsed.data.errorMessage !== 'None' ? parsed.data.errorMessage : null
  return { ok: true as const, entries: parsed.data.entries ?? [], error }
}

// Harmless check for the admin settings page: reads the account balance,
// which only works when the username and API key belong together.
export async function probeVoice(config: VoiceConfig) {
  const host = config.username === 'sandbox' ? 'https://api.sandbox.africastalking.com' : 'https://api.africastalking.com'
  const res = await fetch(`${host}/version1/user?username=${encodeURIComponent(config.username)}`, {
    headers: { apiKey: config.apiKey, Accept: 'application/json' },
    signal: AbortSignal.timeout(15_000),
  })
  const text = await res.text()
  let balance: string | null = null
  try {
    balance = z.object({ UserData: z.object({ balance: z.string() }) }).parse(JSON.parse(text)).UserData.balance
  } catch {
    // Rejected logins come back as plain text.
  }
  return { ok: res.ok && balance !== null, status: res.status, balance, detail: balance ? null : text.slice(0, 200) }
}

// Deducts 5 credits per number up front, places the calls in batches and
// refunds every call Africa's Talking refuses. Calls that are placed but never
// answered are refunded later by handleVoiceCallback.
export async function sendVoiceCampaign(input: { userId: string; message: string; voice: Voice; recipients: string[] }) {
  const { userId, message, voice, recipients } = input
  const config = await getVoiceConfig()
  if (!VOICE_FIELDS.every((f) => config[f.key])) {
    throw new SendError('Voice SMS is not available yet. Please try again later.', 'voice_not_configured', 503)
  }
  if (recipients.length === 0) throw new SendError('Add at least one valid Ghana phone number.', 'no_valid_recipients', 422)
  if (recipients.length > MAX_VOICE_RECIPIENTS) {
    throw new SendError(`You can call at most ${MAX_VOICE_RECIPIENTS.toLocaleString()} numbers at once.`, 'too_many_recipients', 422)
  }
  if (message.length > MAX_VOICE_CHARS) {
    throw new SendError(`Voice messages can be at most ${MAX_VOICE_CHARS} characters.`, 'message_too_long', 422)
  }

  const cost = recipients.length * VOICE_CREDITS_PER_RECIPIENT
  if (!(await spendCredits(userId, cost))) {
    throw new SendError(`You need ${cost.toLocaleString()} credits for this send. Top up your balance first.`, 'insufficient_credits', 402)
  }

  const [campaign] = await db
    .insert(campaigns)
    .values({
      userId,
      senderId: config.phoneNumber,
      message,
      recipients,
      recipientCount: recipients.length,
      segments: 1,
      creditsUsed: cost,
      source: 'dashboard',
      channel: 'voice',
      voice,
    })
    .returning({ id: campaigns.id })

  let placed = 0
  let authFailed = false
  let lastError: string | null = null
  for (let i = 0; i < recipients.length; i += BATCH_SIZE) {
    const batch = recipients.slice(i, i + BATCH_SIZE)
    // Rows exist before dialling so a quickly answered call finds its message.
    const rows = await db
      .insert(voiceCalls)
      .values(batch.map((phoneNumber) => ({ campaignId: campaign.id, userId, phoneNumber })))
      .returning({ id: voiceCalls.id, phoneNumber: voiceCalls.phoneNumber })
    let queued = new Map<string, string>()
    try {
      const result = await placeCalls(config, batch.map((r) => `+${r}`), `V${campaign.id}`)
      if (result.ok) {
        if (result.error) lastError = result.error
        queued = new Map(
          result.entries
            .filter((e) => e.status.toLowerCase() === 'queued' && e.sessionId)
            .map((e) => [e.phoneNumber.replace(/^\+/, ''), e.sessionId!]),
        )
        const refused = result.entries.find((e) => e.status.toLowerCase() !== 'queued')
        if (refused) lastError = `Some calls were refused: ${refused.status}.`
      } else {
        lastError = result.reason
      }
      if (!result.ok && result.authFailed) authFailed = true
    } catch (error) {
      lastError = error instanceof Error ? error.message : 'The voice service is unavailable.'
    }
    for (const row of rows) {
      const sessionId = queued.get(row.phoneNumber)
      await db
        .update(voiceCalls)
        .set(sessionId ? { sessionId } : { status: 'failed', hangupCause: 'NOT_PLACED', updatedAt: new Date() })
        .where(eq(voiceCalls.id, row.id))
    }
    placed += rows.filter((row) => queued.has(row.phoneNumber)).length
    if (authFailed) break
  }

  const refunded = (recipients.length - placed) * VOICE_CREDITS_PER_RECIPIENT
  await refundCredits(userId, refunded)
  const status = placed === 0 ? 'failed' : placed < recipients.length ? 'partial' : 'sent'
  await db
    .update(campaigns)
    // Relative, because missed-call refunds may already have lowered it.
    .set({ status, creditsUsed: sql`${campaigns.creditsUsed} - ${refunded}`, providerResponse: lastError })
    .where(eq(campaigns.id, campaign.id))

  return { id: campaign.id, status: status as 'sent' | 'partial' | 'failed', placed, total: recipients.length, creditsUsed: cost - refunded, error: lastError }
}

function escapeXml(text: string) {
  return text.replace(/[<>&"']/g, (ch) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;', "'": '&apos;' })[ch]!)
}

function xml(body: string) {
  return new Response(`<?xml version="1.0" encoding="UTF-8"?><Response>${body}</Response>`, {
    headers: { 'Content-Type': 'application/xml' },
  })
}

// Africa's Talking posts here when a call is answered (isActive=1) and again
// when it ends (isActive=0). Only calls we placed get a message read out.
export async function handleVoiceCallback(params: URLSearchParams) {
  const sessionId = params.get('sessionId')
  const columns = {
    id: voiceCalls.id,
    sessionId: voiceCalls.sessionId,
    status: voiceCalls.status,
    message: campaigns.message,
    voice: campaigns.voice,
    campaignId: campaigns.id,
    userId: voiceCalls.userId,
  }
  let [call] = sessionId
    ? await db.select(columns).from(voiceCalls).innerJoin(campaigns, eq(campaigns.id, voiceCalls.campaignId)).where(eq(voiceCalls.sessionId, sessionId))
    : []
  // A call answered before its session ID was saved is matched by the send
  // (clientRequestId "V<id>") and the number that was called.
  const campaignId = Number(params.get('clientRequestId')?.match(/^V(\d+)$/)?.[1])
  const destination = params.get('destinationNumber')?.replace(/^\+/, '')
  if (!call && sessionId && campaignId && destination) {
    ;[call] = await db
      .select(columns)
      .from(voiceCalls)
      .innerJoin(campaigns, eq(campaigns.id, voiceCalls.campaignId))
      .where(and(eq(voiceCalls.campaignId, campaignId), eq(voiceCalls.phoneNumber, destination), sql`${voiceCalls.sessionId} is null`))
    if (call) await db.update(voiceCalls).set({ sessionId }).where(eq(voiceCalls.id, call.id))
  }
  if (!call) return xml('<Reject/>')

  if (params.get('isActive') === '1') {
    await db
      .update(voiceCalls)
      .set({ status: 'answered', updatedAt: new Date() })
      .where(and(eq(voiceCalls.id, call.id), eq(voiceCalls.status, 'queued')))
    const voice = call.voice === 'man' ? 'man' : 'woman'
    return xml(`<Say voice="${voice}" playBeep="false">${escapeXml(call.message)}</Say>`)
  }

  const duration = Number(params.get('durationInSeconds'))
  const durationSeconds = Number.isFinite(duration) ? Math.round(duration) : null
  const hangupCause = params.get('hangupCause')?.slice(0, 100) ?? null
  const answered = call.status === 'answered' || (durationSeconds ?? 0) > 0

  if (answered) {
    await db
      .update(voiceCalls)
      .set({ status: 'completed', durationSeconds, hangupCause, updatedAt: new Date() })
      .where(and(eq(voiceCalls.id, call.id), inArray(voiceCalls.status, ['queued', 'answered'])))
    return xml('')
  }

  // The conditional update makes the refund happen once, even if the final
  // callback is delivered twice.
  const [missed] = await db
    .update(voiceCalls)
    .set({ status: 'failed', durationSeconds, hangupCause, updatedAt: new Date() })
    .where(and(eq(voiceCalls.id, call.id), eq(voiceCalls.status, 'queued')))
    .returning({ id: voiceCalls.id })
  if (missed) {
    await refundCredits(call.userId, VOICE_CREDITS_PER_RECIPIENT)
    await db
      .update(campaigns)
      .set({ creditsUsed: sql`greatest(${campaigns.creditsUsed} - ${VOICE_CREDITS_PER_RECIPIENT}, 0)` })
      .where(eq(campaigns.id, call.campaignId))
  }
  return xml('')
}

// Answered / missed counts per voice send, for the history tables.
export async function voiceCallCounts(campaignIds: number[]) {
  if (campaignIds.length === 0) return new Map<number, { answered: number; missed: number }>()
  const rows = await db
    .select({
      campaignId: voiceCalls.campaignId,
      answered: sql<number>`count(*) filter (where ${voiceCalls.status} in ('answered', 'completed'))::int`,
      missed: sql<number>`count(*) filter (where ${voiceCalls.status} = 'failed')::int`,
    })
    .from(voiceCalls)
    .where(inArray(voiceCalls.campaignId, campaignIds))
    .groupBy(voiceCalls.campaignId)
  return new Map(rows.map((r) => [r.campaignId, { answered: r.answered, missed: r.missed }]))
}
