-- ==========================================================================
-- Agencia PSI — Migracao: Retroativa WhatsApp-linked em contact_phones
-- ==========================================================================
-- Criado por: Leonardo Nohama
-- Data: 2026-04-21 · Sao Carlos/SP — Brasil
--
-- Pacientes que foram vinculados via drawer de conversa ANTES do refactor
-- polimorfico de telefones tiveram o numero preservado em patients.telefone
-- mas sem marca "vinculado WhatsApp" (nao existia o conceito).
--
-- Este script:
--   1. Detecta pacientes com conversation_messages (direction=inbound)
--   2. Encontra o contact_phone que match o numero da conversa
--   3. Muda o contact_type_id pra 'whatsapp' + seta whatsapp_linked_at
--      pra first_message_received_at
--
-- Nao destrutivo: so altera phones que claramente foram vinculados via CRM.
-- Se paciente tem multiplos phones, apenas o que match o numero da conversa
-- e afetado.
-- ==========================================================================

DO $$
DECLARE
    v_whatsapp_type_id UUID;
BEGIN
    SELECT id INTO v_whatsapp_type_id
        FROM public.contact_types
        WHERE slug = 'whatsapp' AND tenant_id IS NULL
        LIMIT 1;

    IF v_whatsapp_type_id IS NULL THEN
        RAISE NOTICE 'Contact type WhatsApp nao encontrado — pule a migration retroativa';
        RETURN;
    END IF;

    -- Atualiza contact_phones que match conversation_messages inbound
    WITH convs AS (
        SELECT
            cm.patient_id,
            regexp_replace(cm.from_number, '\D', '', 'g') AS phone_digits,
            MIN(COALESCE(cm.received_at, cm.created_at)) AS first_msg_at
        FROM public.conversation_messages cm
        WHERE cm.patient_id IS NOT NULL
          AND cm.direction = 'inbound'
          AND cm.from_number IS NOT NULL
          AND cm.channel = 'whatsapp'
        GROUP BY cm.patient_id, regexp_replace(cm.from_number, '\D', '', 'g')
    )
    UPDATE public.contact_phones cp
    SET
        contact_type_id = v_whatsapp_type_id,
        whatsapp_linked_at = COALESCE(cp.whatsapp_linked_at, convs.first_msg_at)
    FROM convs
    WHERE cp.entity_type = 'patient'
      AND cp.entity_id = convs.patient_id
      AND cp.number = convs.phone_digits;

    -- Log
    RAISE NOTICE 'Retroactive WhatsApp link complete';
END $$;

-- ==========================================================================
-- FIM DA MIGRACAO
-- ==========================================================================
