-- Canonicalize RFC Message-IDs so threading lookups (angle-bracket form) match stored values.
UPDATE messages
SET message_id = '<' || trim(both '<>' from trim(message_id)) || '>',
    updated_at = NOW()
WHERE message_id <> ''
  AND message_id NOT LIKE '<%>';

-- Re-link split threads from in_reply_to / references (repeat for nested replies).
DO $$
DECLARE
  i INT;
  n BIGINT;
BEGIN
  FOR i IN 1..8 LOOP
    UPDATE messages child
    SET thread_id = parent.thread_id, updated_at = NOW()
    FROM messages parent
    WHERE child.account_id = parent.account_id
      AND parent.thread_id IS NOT NULL
      AND child.thread_id IS DISTINCT FROM parent.thread_id
      AND (
        (child.in_reply_to <> '' AND child.in_reply_to = parent.message_id)
        OR parent.message_id = ANY(child.references_header)
      );
    GET DIAGNOSTICS n = ROW_COUNT;
    EXIT WHEN n = 0;
  END LOOP;
END $$;
