export interface MessageTemplate {
  id: string;
  restaurantId: string;
  templateKey: string;
  channel: string;
  content: string;
  createdAt: string;
  updatedAt: string;
}

function normalizeTemplate(row: Record<string, unknown>): MessageTemplate {
  return {
    id: row.id as string,
    restaurantId: (row.restaurant_id ?? row.restaurantId) as string,
    templateKey: (row.template_key ?? row.templateKey) as string,
    channel: row.channel as string,
    content: row.content as string,
    createdAt: (row.created_at ?? row.createdAt) as string,
    updatedAt: (row.updated_at ?? row.updatedAt) as string,
  };
}

export async function listTemplates(): Promise<MessageTemplate[]> {
  const res = await fetch('/api/templates');
  if (!res.ok) throw new Error('Failed to fetch templates');
  const data = await res.json();
  return (data.templates ?? []).map((t: Record<string, unknown>) => normalizeTemplate(t));
}

export async function saveTemplates(
  templates: { templateKey: string; channel: string; content: string }[]
): Promise<MessageTemplate[]> {
  const res = await fetch('/api/templates', {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ templates }),
  });
  if (!res.ok) throw new Error('Failed to save templates');
  const data = await res.json();
  return (data.templates ?? []).map((t: Record<string, unknown>) => normalizeTemplate(t));
}
