-- Deploy numerus:tax to pg
-- requires: schema_numerus
-- requires: company
-- requires: tax_rate

begin;

set search_path to numerus, public;

create table tax (
	tax_id serial primary key,
	company_id integer not null references company,
	name text not null constraint name_not_empty check(length(trim(name)) > 0),
	rate tax_rate not null
);

grant select, insert, update, delete on table tax to invoicer;
grant select, insert, update, delete on table tax to admin;

grant usage on sequence tax_tax_id_seq to invoicer;
grant usage on sequence tax_tax_id_seq to admin;

alter table tax enable row level security;

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

commit;
