--
-- forums_message_search__utrg/0
--
create or replace function forums_message_search__utrg(
  
) returns trigger as $$

DECLARE
    v_root_message_id forums_messages.message_id%TYPE;
    v_is_approved     boolean;
BEGIN
    if old.parent_id is null and new.state <> 'approved' then
         -- New threads that have been revoked approval should be
         -- removed from the search results.
         perform search_observer__enqueue(old.message_id,'DELETE');
    else
        -- Non-root messages trigger the indexing of the whole thread,
        -- but only if the thread (the root message) has been
        -- approved.
        -- We do not care about the approval of the message itself in
        -- this case, as the datasource callback will take care of not
        -- rendering any unapproved non-root message.
        v_root_message_id := forums_message__root_message_id(new.parent_id);

        select state = 'approved' into v_is_approved
          from forums_messages
         where message_id = v_root_message_id;

        if v_is_approved then
            perform search_observer__enqueue(v_root_message_id,'UPDATE');
        end if;
    end if;
    return old;
END;
$$ language plpgsql;