begin;

create or replace function messages_fulltext(msg messages) returns tsvector
language plpgsql immutable as $$
begin
    return setweight(to_tsvector('russian', regexp_replace(
        coalesce(msg.props->>'from', '') || ' ' ||
        coalesce(msg.props->>'replyto', '') || ' ' ||
        coalesce(msg.props->>'to', '') || ' ' ||
        coalesce(msg.props->>'cc', '') || ' ' ||
        coalesce(msg.props->>'bcc', '') || ' ' ||
        (select string_agg((a->>'name') || ' ' || (a->>'mimetype') || ' ' || (a->>'size'), ' ')
        from jsonb_array_elements(coalesce(msg.props->'attachments', '[]'::jsonb)) as t (a)) || ' ' ||
        msg.subject,
        '\W+', ' ', 'g'
    )), 'A')
    || setweight(to_tsvector('russian', msg.body_html_text || ' ' || msg.body_text), 'B');
end
$$;

update messages
set props = props || jsonb_build_object('attachments', (
    select jsonb_agg(jsonb_build_object('name', a->>0, 'mimetype', a->>1, 'size', a->>2)) from jsonb_array_elements(props->'attachments') as t (a)
))
where jsonb_array_length(props->'attachments') > 0;

commit;
