-- Deploy numerus:collection to pg
-- requires: roles
-- requires: schema_numerus
-- requires: company
-- requires: payment_account
-- requires: currency
-- requires: tag_name
-- requires: payment_status
-- requires: extension_pgcrypto

begin;

set search_path to numerus, public;

create table collection (
	collection_id integer generated by default as identity primary key,
	company_id integer not null references company,
	slug uuid not null unique default gen_random_uuid(),
	description text not null,
	collection_date date not null default current_date,
	payment_account_id integer not null references payment_account,
	amount integer not null constraint collection_amount_positive check (amount > 0),
	currency_code text not null references currency,
	tags tag_name[] not null default '{}',
	payment_status text not null default 'complete' references payment_status,
	created_at timestamptz not null default current_timestamp
);

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

alter table collection enable row level security;

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

commit;
