-- Deploy camper:user_profile to pg
-- requires: roles
-- requires: schema_camper
-- requires: user
-- requires: company_user
-- requires: current_user_email
-- requires: current_user_cookie
-- requires: current_company_id

begin;

set search_path to camper, public;

create or replace view user_profile with (security_barrier) as
	select user_id
	     , company_id
	     , email
	     , name
	     , role
	     , lang_tag
	     , left(cookie, 10) as csrf_token
	from auth."user"
	join company_user using (user_id)
	where email = current_user_email()
	  and cookie = current_user_cookie()
	  and cookie_expires_at > current_timestamp
	  and length(cookie) > 30
	  and company_id = current_company_id()
union all
	select 0
	     , 0
	     , null::email
	     , ''
	     , 'guest'::name
	     , 'und'
	     , ''
	where not exists (select 1
		          from auth."user"
		          where email = current_user_email()
		            and cookie = current_user_cookie()
		            and cookie_expires_at > current_timestamp
		            and length(cookie) > 30)
;

grant select on table user_profile to guest;
grant select, update (email, name, lang_tag) on table user_profile to employee;
grant select, update (email, name, lang_tag) on table user_profile to admin;

create or replace function update_user_profile() returns trigger as
$$
begin
	update auth."user"
	set email    = new.email
	  , name     = new.name
	  , lang_tag = new.lang_tag
	where email = current_user_email()
	  and cookie = current_user_cookie()
	  and cookie_expires_at > current_timestamp
	  and length(cookie) > 30
	;

	perform set_config('request.user.email', new.email, false);

	return new;
end;
$$
language plpgsql
security definer
set search_path to auth, camper, pg_temp;

create trigger update_user_profile
instead of update
on user_profile
for each row
execute procedure update_user_profile();

commit;