import { createClient } from "@/lib/supabase-server";

const COLUMN_NAME = "whatsapp_templates";

export interface WhatsAppTemplates {
  product_inquiry?: string;
  cart_checkout_header?: string;
  cart_checkout_footer?: string;
  quote_share?: string;
  order_status?: string;
}

const DEFAULTS: WhatsAppTemplates = {
  product_inquiry: "Olá! Tenho interesse no produto {{nome_produto}}",
  cart_checkout_header: "*Novo Pedido*",
  cart_checkout_footer: "{{resumo_itens}}\n\n{{subtotal}}\n{{desconto}}\n*Total: {{total}}*",
  quote_share: "Olá! Segue o orçamento #{{numero_orcamento}}. Total: {{total}}.{{validade}}{{condicoes}} {{link}}",
  order_status:
    "Olá! Segue atualização sobre seu pedido #{{numero_pedido}}. Status atual: *{{status}}*. Acompanhe o progresso em tempo real: {{link}}",
};

export function getDefaultTemplates(): WhatsAppTemplates {
  return { ...DEFAULTS };
}

export function resolveTemplate(
  template: string | undefined,
  defaultTemplate: string,
  vars: Record<string, string>
): string {
  let message = template || defaultTemplate;
  for (const [key, value] of Object.entries(vars)) {
    message = message.replaceAll(`{{${key}}}`, value);
  }
  return message;
}

export async function loadWhatsAppTemplates(profileId: string): Promise<WhatsAppTemplates> {
  try {
    const supabase = await createClient();
    const { data, error } = await supabase
      .from("profiles")
      .select(COLUMN_NAME)
      .eq("id", profileId)
      .maybeSingle();

    if (error || !data) return { ...DEFAULTS };

    const raw = (data as Record<string, unknown>)[COLUMN_NAME];
    if (!raw || typeof raw !== "object") return { ...DEFAULTS };

    return { ...DEFAULTS, ...(raw as WhatsAppTemplates) };
  } catch {
    return { ...DEFAULTS };
  }
}
