/**
 * Marketing WhatsApp send wrapper.
 *
 * Marketing broadcasts ALWAYS go out as templates — Meta forbids freeform
 * outbound text outside the 24-hour customer-initiated session window.
 * Variable substitution is positional ({{1}}, {{2}}, ...) per Meta spec.
 */

import { sendWhatsAppTemplate } from '@server/services/whatsapp.service';

interface SendCampaignWhatsAppInput {
  branchId: string;
  toE164: string;
  templateName: string;
  templateLang: string;
  templateVars: string[];
}

export async function sendCampaignWhatsApp(
  input: SendCampaignWhatsAppInput
): Promise<{ messageId: string | null; error?: string }> {
  if (!input.toE164) return { messageId: null, error: 'missing recipient phone' };
  if (!input.templateName) return { messageId: null, error: 'missing template name' };

  const components = input.templateVars.length > 0
    ? [{
        type: 'body' as const,
        parameters: input.templateVars.map((v) => ({ type: 'text' as const, text: v })),
      }]
    : [];

  try {
    const result = await sendWhatsAppTemplate(
      input.branchId, input.toE164, input.templateName, input.templateLang || 'en', components
    );
    return { messageId: result.messageId, error: result.error };
  } catch (err) {
    return { messageId: null, error: err instanceof Error ? err.message : String(err) };
  }
}
