-- ============================================================
-- Migration 014: Workflow de aprovação de templates WhatsApp
-- Tabela: whatsapp_templates
-- ============================================================

ALTER TABLE whatsapp_templates
  ADD COLUMN IF NOT EXISTS area_id INTEGER REFERENCES areas (id) ON DELETE SET NULL,
  ADD COLUMN IF NOT EXISTS status VARCHAR(40) NOT NULL DEFAULT 'approved',
  ADD COLUMN IF NOT EXISTS requested_by_role VARCHAR(40),
  ADD COLUMN IF NOT EXISTS admin_approved_at TIMESTAMP WITH TIME ZONE,
  ADD COLUMN IF NOT EXISTS meta_submitted_at TIMESTAMP WITH TIME ZONE,
  ADD COLUMN IF NOT EXISTS meta_approved_at TIMESTAMP WITH TIME ZONE;

UPDATE whatsapp_templates
SET
  status = COALESCE(status, 'approved'),
  meta_approved_at = COALESCE(meta_approved_at, updated_at, created_at, CURRENT_TIMESTAMP)
WHERE status = 'approved';

CREATE INDEX IF NOT EXISTS idx_whatsapp_templates_area ON whatsapp_templates (area_id);
CREATE INDEX IF NOT EXISTS idx_whatsapp_templates_status ON whatsapp_templates (status);
