-- Deploy camper:invoice_product to pg
-- requires: schema_camper
-- requires: invoice
-- requires: discount_rate

begin;

set search_path to camper, public;

create table invoice_product (
	invoice_product_id integer generated by default as identity primary key,
	invoice_id integer not null references invoice,
	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 employee;
grant select, insert, update, delete on table invoice_product to admin;

grant usage on sequence invoice_product_invoice_product_id_seq to employee;
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;
