-- Deploy numerus:invoice_product to pg
-- requires: schema_numerus
-- requires: invoice
-- requires: discount_rate

begin;

set search_path to numerus, public;

create table invoice_product (
	invoice_product_id serial primary key,
	invoice_id integer not null references invoice,
	product_id integer not null references product,
	name text not null constraint name_not_empty check(length(trim(name)) > 0),
	description text not null default '',
	price integer not null,
	quantity integer not null default 1,
	discount_rate discount_rate not null default 0.0
);

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

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

alter table invoice_product enable row level security;

create policy company_policy
on invoice_product
using (
	exists(
		select 1
		from invoice
		where invoice.invoice_id = invoice_product.invoice_id
	)
);

commit;
