/**
 * Inbound message routing — system-communications-notifications (Task 16).
 *
 * Routes inbound webhook messages to downstream services based on tenant config.
 * The downstream seams (`createSupportTicket`, `dispatchToAiAssistant`) are
 * injected via dependency injection — their implementations live in
 * crm-support-center and ai-assistant respectively.
 */
import type { InboundMessage } from '@zync/types'

export interface TenantCommsConfig {
  autoCreateTickets: boolean
  aiAssistantEnabled: boolean
  telegramAiChatId?: string | null
}

/** Seam for CRM ticket creation — implemented by crm-support-center (spec 40). */
export type CreateSupportTicketFn = (msg: InboundMessage) => Promise<{ ticketId: string }>

/** Seam for AI assistant dispatch — implemented by ai-assistant spec. */
export type DispatchToAiAssistantFn = (msg: InboundMessage) => Promise<void>

export interface RoutingDeps {
  createSupportTicket: CreateSupportTicketFn
  dispatchToAiAssistant: DispatchToAiAssistantFn
}

/**
 * Route an inbound message according to tenant config.
 * Both paths can fire for the same message — they are independent.
 */
export async function routeInboundMessage(
  msg: InboundMessage,
  cfg: TenantCommsConfig,
  deps: RoutingDeps,
): Promise<void> {
  const ops: Promise<unknown>[] = []

  if (cfg.autoCreateTickets) {
    ops.push(deps.createSupportTicket(msg))
  }

  if (cfg.aiAssistantEnabled) {
    ops.push(deps.dispatchToAiAssistant(msg))
  }

  // Run concurrently; individual failures propagate (Queue retries on throw).
  await Promise.all(ops)
}
