/**
 * Client-side API wrapper for the WhatsApp template cache (Task #472).
 * Mirrors the route handlers at /api/channels/whatsapp/templates.
 */

export interface WaTemplateComponent {
  type: string;
  format?: string;
  text?: string;
  buttons?: unknown[];
  example?: unknown;
}

export interface WhatsAppTemplate {
  id: string;
  restaurant_id: string;
  branch_id: string;
  name: string;
  language: string;
  status: string;
  components: WaTemplateComponent[];
  synced_at: string;
}

/** Extract the {{N}} placeholders from the BODY component text. */
export function extractBodyVars(template: WhatsAppTemplate): number[] {
  const body = template.components.find((c) => c.type === 'BODY');
  if (!body?.text) return [];
  const matches = body.text.match(/\{\{(\d+)\}\}/g) ?? [];
  const nums = matches.map((m) => parseInt(m.replace(/\D/g, ''), 10));
  return [...new Set(nums)].sort((a, b) => a - b);
}

/** Return header text for display reference, if present. */
export function getHeaderText(template: WhatsAppTemplate): string | null {
  const header = template.components.find((c) => c.type === 'HEADER' && c.format === 'TEXT');
  return header?.text ?? null;
}

/** Return footer text for display reference, if present. */
export function getFooterText(template: WhatsAppTemplate): string | null {
  const footer = template.components.find((c) => c.type === 'FOOTER');
  return footer?.text ?? null;
}

async function jsonFetch<T>(url: string, init?: RequestInit): Promise<T> {
  const res = await fetch(url, {
    ...init,
    headers: { 'Content-Type': 'application/json', ...(init?.headers ?? {}) },
  });
  const text = await res.text();
  let parsed: unknown = null;
  if (text) { try { parsed = JSON.parse(text); } catch { /* */ } }
  if (!res.ok) {
    const body = (parsed ?? {}) as { error?: string };
    throw new Error(body.error ?? `Request failed (${res.status})`);
  }
  return parsed as T;
}

export interface TemplateListResult {
  /** true = branch has WABA credentials; false = not connected */
  connected: boolean;
  templates: WhatsAppTemplate[];
}

/** Fetch the locally-cached template list for a branch, including WABA status. */
export async function listWhatsAppTemplates(branchId: string): Promise<TemplateListResult> {
  const data = await jsonFetch<TemplateListResult>(
    `/api/channels/whatsapp/templates?branch_id=${encodeURIComponent(branchId)}`
  );
  return data;
}

/** Trigger a Meta Graph API sync, then return the updated list. */
export async function syncWhatsAppTemplates(branchId: string): Promise<WhatsAppTemplate[]> {
  const data = await jsonFetch<{ templates: WhatsAppTemplate[] }>(
    '/api/channels/whatsapp/templates',
    { method: 'POST', body: JSON.stringify({ branch_id: branchId }) }
  );
  return data.templates;
}
