-- Deploy numerus:invoice_number_counter to pg
-- requires: schema_numerus
-- requires: company

begin;

set search_path to numerus, public;

create table invoice_number_counter (
	company_id integer not null,
	year integer not null constraint year_always_positive check(year > 0),
	currval integer not null constraint counter_always_positive check(currval > 0),
	primary key (company_id, year)
);

grant select, insert, update on table invoice_number_counter to invoicer;
grant select, insert, update on table invoice_number_counter to admin;

alter table invoice_number_counter enable row level security;

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

commit;
