drop function if exists sp_post_user_comment(
	p_parent_user_comment_detail_id integer,
	p_poster_user_id integer,
	p_target_user_id integer,
	p_user_comment text,
	p_score double precision );

create function sp_post_user_comment(
	p_parent_user_comment_detail_id integer,
	p_poster_user_id integer,
	p_target_user_id integer,
	p_user_comment text,
	p_score double precision ) returns integer as $$
declare
	retval integer;
	rec record;
begin
	if p_parent_user_comment_detail_id is null then
		insert into user_comment_details(
			poster_user_id,
			target_user_id,
			parent_user_comment_detail_id,
			user_comment_detail,
			score ) values (
			p_poster_user_id,
			p_target_user_id,
			p_parent_user_comment_detail_id,
			p_user_comment,
			p_score );
	else
		insert into user_comment_details(
			poster_user_id,
			target_user_id,
			parent_user_comment_detail_id,
			user_comment_detail ) values (
			p_poster_user_id,
			p_target_user_id,
			p_parent_user_comment_detail_id,
			p_user_comment );
	end if;
	select currval( 'user_comment_details_user_comment_detail_id_seq') into retval;

	if p_parent_user_comment_detail_id is null then
		select * into rec from user_comments where user_id=p_target_user_id;
		if rec is null then
			insert into user_comments(
				user_id,
				score_overall,
				score_average ) values (
				p_target_user_id,
				p_score,
				p_score );
		else
			update user_comments set
				mtstamp=now(),
				number_of_comments=rec.number_of_comments+1,
				score_overall=rec.score_overall+p_score,
				score_average=(rec.score_overall+p_score)/(rec.number_of_comments+1)
			where
				user_id=p_target_user_id;
		end if;
	end if;
	return retval;
end;
$$ language plpgsql;
