-- Deploy numerus:user_profile to pg
-- requires: schema_numerus
-- requires: user
-- requires: current_app_user

begin;

set search_path to numerus, public;

create or replace view user_profile
with (security_barrier)
as
select user_id
     , email
     , name
     , role
     , lang_tag
from auth."user"
where cookie = current_app_user()
  and cookie_expires_at > current_timestamp
  and length(cookie) > 30
union all
select 0
     , null::email
     , ''
     , 'guest'::name
     , 'und'
where not exists (
	select 1
	from auth."user"
	where cookie = current_app_user()
	  and cookie_expires_at > current_timestamp
	  and length(cookie) > 30
);

create rule update_user_profile as on update to user_profile
do instead update auth."user"
set email = new.email
  , name = new.name
  , lang_tag = new.lang_tag
where cookie = current_app_user()
  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 invoicer;
grant select, update(email, name, lang_tag) on table user_profile to admin;

commit;
