-- =============================================================================
-- Migration: 20260420000009_conv_messages_delivery_status
--
-- Adiciona colunas para rastrear status de entrega/leitura das mensagens
-- outbound (envio pelo sistema). Evolution dispara evento messages.update
-- com status = SENT | DELIVERED | READ que vamos capturar.
-- =============================================================================

ALTER TABLE public.conversation_messages
    ADD COLUMN IF NOT EXISTS delivered_at TIMESTAMPTZ,
    ADD COLUMN IF NOT EXISTS read_by_recipient_at TIMESTAMPTZ,
    ADD COLUMN IF NOT EXISTS delivery_status TEXT
        CHECK (delivery_status IS NULL OR delivery_status IN ('pending','sent','delivered','read','failed'));

CREATE INDEX IF NOT EXISTS idx_conv_msg_delivery_status
    ON public.conversation_messages (tenant_id, delivery_status)
    WHERE direction = 'outbound';
