import { createFileRoute } from '@tanstack/react-router'
import { handleVoiceCallback } from '@/lib/voice.server'

// Africa's Talking calls this URL (set on the voice number in their dashboard)
// when a call is answered and when it ends. It replies with the XML that reads
// the message aloud.
export const Route = createFileRoute('/api/voice/callback')({
  server: {
    handlers: {
      POST: async ({ request }) => {
        let params: URLSearchParams
        try {
          const type = request.headers.get('content-type') ?? ''
          params = type.includes('application/json')
            ? new URLSearchParams(Object.entries((await request.json()) as Record<string, string>).map(([k, v]) => [k, String(v)]))
            : new URLSearchParams(await request.text())
        } catch {
          return new Response('Invalid payload', { status: 400 })
        }
        try {
          return await handleVoiceCallback(params)
        } catch (error) {
          console.error('Voice callback processing failed', error)
          return new Response('Processing failed', { status: 500 })
        }
      },
    },
  },
})
