-- Migration 026: WhatsApp HSM Templates + WABA ID
-- Adiciona suporte a templates HSM da Meta com botões, header, footer e variáveis estruturadas.

-- WABA ID na config (necessário para gerenciar templates via API)
ALTER TABLE whatsapp_config
  ADD COLUMN IF NOT EXISTS waba_id VARCHAR(100);

-- Colunas HSM na tabela de templates
ALTER TABLE whatsapp_templates
  ADD COLUMN IF NOT EXISTS language          VARCHAR(10)  NOT NULL DEFAULT 'pt_BR',
  ADD COLUMN IF NOT EXISTS meta_template_name VARCHAR(512),
  ADD COLUMN IF NOT EXISTS meta_template_id   VARCHAR(100),
  ADD COLUMN IF NOT EXISTS meta_status        VARCHAR(50),
  ADD COLUMN IF NOT EXISTS header_type        VARCHAR(20),
  ADD COLUMN IF NOT EXISTS header_text        TEXT,
  ADD COLUMN IF NOT EXISTS footer_text        TEXT,
  ADD COLUMN IF NOT EXISTS buttons            JSONB,
  ADD COLUMN IF NOT EXISTS body_variables     JSONB;

-- Templates existentes sem meta_template_name ficam como rascunho
UPDATE whatsapp_templates
  SET status = 'draft'
  WHERE status IN ('approved', 'meta_review', 'admin_review')
    AND meta_template_name IS NULL;

-- Índice único para meta_template_name (ignora NULLs)
CREATE UNIQUE INDEX IF NOT EXISTS whatsapp_templates_meta_name_idx
  ON whatsapp_templates (meta_template_name)
  WHERE meta_template_name IS NOT NULL;
