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

DECLARE
    v_root_message_id forums_messages.message_id%TYPE;
    v_is_approved     boolean;
BEGIN
    -- if the deleted msg has a parent then its an UPDATE to a thread, otherwise a DELETE.

    if old.parent_id is null then
        perform search_observer__enqueue(old.message_id,'DELETE');
    else
        -- Deleting non-root messages triggers 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;