--- recalc-unread

-- decrement unread
update chats
set client_unread = client_unread - (
    select count(*) 
    from chat_messages m
    where
        m.chat_id = chats.id
        and m."read" = false
        and m.ticket_message_id is null
)
where chats.client_unread > 0;

-- mark mailing messages as read
update chat_messages
set
    "read" = true
where
    "read" = false
    and ticket_message_id is null;
