
-- chat messages type
drop type if exists sp_t_chat_message cascade;
create type sp_t_chat_message as (
	chat_message_id integer,
	chatroom_id integer,
	ctstamp timestamp without time zone,
	poster_user_id integer,
	target_user_id integer,
	is_system boolean,
	message text

);
-- get latest chat message type
drop function if exists sp_r_chat_get_latest_messages(
	p_chatroom_ids integer array,
	p_user_id integer,
	p_last_chat_message_id integer );

create or replace function sp_r_chat_get_latest_messages(
	p_chatroom_ids integer array,
	p_user_id integer,
	p_last_chat_message_id integer ) returns setof sp_t_chat_message as $$
declare
	rec sp_t_chat_message;
	recset refcursor;
	query varchar;
begin
	query:='select * from chat_messages where chat_message_id>'||p_last_chat_message_id||' order by chat_message_id';
	open recset for execute query;
	loop
		fetch recset into rec;
		exit when not found;
		-- chatroom filter
		if rec.chatroom_id is not null then
			if array[ rec.chatroom_id ] <@ p_chatroom_ids then
				return next rec;
			end if;
		end if;
		if rec.target_user_id is not null then
			if rec.target_user_id = p_user_id then
				return next rec;
			end if;
		end if;
	end loop;
	close recset;
	return;
end;
$$language plpgsql;
