-- Deploy numerus:quote to pg
-- requires: roles
-- requires: schema_numerus
-- requires: company
-- requires: quote_status
-- requires: currency
-- requires: tag_name

begin;

set search_path to numerus, public;

create table quote (
	quote_id serial primary key,
	company_id integer not null references company,
	slug uuid not null unique default gen_random_uuid(),
	quote_number text not null constraint quote_number_not_empty check(length(trim(quote_number)) > 1),
	quote_date date not null default current_date,
	quote_status text not null default 'created' references quote_status,
	terms_and_conditions text not null default '',
	notes text not null default '',
	tags tag_name[] not null default '{}',
	currency_code text not null references currency,
	created_at timestamptz not null default current_timestamp
);

create index on quote using gin (tags);

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

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

alter table quote enable row level security;

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

commit;
