-- Check thread fragmentation per SAG
WITH resolved AS (
    SELECT
        se.sag_id,
        em.id,
        em.thread_key,
        em.folder,
        COALESCE(
            NULLIF(REGEXP_REPLACE(TRIM(COALESCE(em.thread_key, '')), '[<>\s]', '', 'g'), ''),
            CONCAT('email-', em.id::text)
        ) AS resolved_key
    FROM sag_emails se
    JOIN email_messages em ON em.id = se.email_id
    WHERE em.deleted_at IS NULL
)
SELECT sag_id, COUNT(DISTINCT resolved_key) as thread_count, COUNT(*) as email_count
FROM resolved
GROUP BY sag_id
HAVING COUNT(DISTINCT resolved_key) > 1
ORDER BY thread_count DESC;
