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

DECLARE
    v_root_message_id forums_messages.message_id%TYPE;
    v_is_approved     boolean;
BEGIN
    if new.parent_id is null and new.state = 'approved' then
        -- New threads are indexed only if they are approved.
        perform search_observer__enqueue(new.message_id,'INSERT');
    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 new;
END;
$$ language plpgsql;