-- Deploy numerus:company_user to pg
-- requires: schema_numerus
-- requires: user
-- requires: company

begin;

set search_path to numerus, auth, public;

create table company_user (
	company_id integer not null references company,
	user_id integer not null references "user",
	primary key (company_id, user_id)
);

grant select on table company_user to invoicer;
grant select on table company_user to admin;


alter table company enable row level security;

create policy company_policy
on company
using (
	exists(
		select 1
		from company_user
		join user_profile using (user_id)
		where company_user.company_id = company.company_id
	)
);

-- TODO:
-- I think we can not do the same for company_user because it would be
-- an infinite loop, but in this case i think it is fine because we can
-- only see ids, nothing more.

commit;
