import Fastify from 'fastify'; import { ingestInbound, ingestStatus, resolveChannel } from '@omniloq/core'; /** * API d'ingestion (Fastify). Le webhook est un POST : validation → normalisation → * TX Message+Job → HTTP 200. Le runtime n'est JAMAIS appelé de façon synchrone ici. * Le JSON Meta est confiné dans l'adaptateur (parseWebhook). */ export function buildServer() { const app = Fastify({ logger: true }); // Vérification webhook (GET) — Meta appelle avec hub.mode/hub.verify_token/hub.challenge app.get('/webhooks/whatsapp/meta/:channelAccountId', async (req, reply) => { const { channelAccountId } = req.params as { channelAccountId: string }; const query = req.query as Record; try { const channel = await resolveChannel(channelAccountId); const { verified, challenge } = channel.verifyWebhook(query); if (verified) return reply.send(challenge ?? ''); return reply.status(403).send('verification failed'); } catch { return reply.status(404).send('unknown channel'); } }); // Ingestion (POST) — ACK immédiat, aucun runtime synchrone app.post('/webhooks/whatsapp/meta/:channelAccountId', async (req, reply) => { const { channelAccountId } = req.params as { channelAccountId: string }; try { const channel = await resolveChannel(channelAccountId); const events = channel.parseWebhook(req.body); for (const event of events) { if (event.type === 'message_received') { await ingestInbound(event.inbound); } else { await ingestStatus(event); } } return reply.send({ status: 'ok' }); } catch { return reply.status(500).send({ error: 'ingest failed' }); } }); return app; }