import { prisma, decryptSecret } from '@omniloq/db'; import { WhatsAppMetaChannel } from '@omniloq/channels'; import type { Channel } from '@omniloq/channels'; /** * Résout un canal à partir d'un ChannelAccount. Le token d'accès vit dans * `ChannelAccount.secretId → Secret.encryptedValue` et est décrypté ici (jamais * dans `config.accessToken`). `fetchImpl` est injectable pour les tests. */ export async function resolveChannel(channelAccountId: string, fetchImpl?: typeof fetch): Promise { const account = await prisma.channelAccount.findUnique({ where: { id: channelAccountId }, include: { secret: true }, }); if (!account) throw new Error('channel account not found'); if (account.channelType !== 'whatsapp') { throw new Error(`unsupported channel type: ${account.channelType}`); } const config = (account.config ?? {}) as Record; const accessToken = account.secret ? decryptSecret(account.secret.encryptedValue) : ''; return new WhatsAppMetaChannel( { phoneNumberId: account.externalAccountId ?? '', accessToken, verifyToken: config.verifyToken, graphApiVersion: config.graphApiVersion, wabaId: config.wabaId, }, fetchImpl ); }