-- Deploy numerus:attach_to_invoice to pg
-- requires: schema_numerus
-- requires: roles
-- requires: invoice
-- requires: invoice_attachment

begin;

set search_path to numerus, public;

create or replace function attach_to_invoice(invoice_slug uuid, original_filename text, mime_type text, content bytea) returns void as
$$
	insert into invoice_attachment (invoice_id, original_filename, mime_type, content)
	select invoice_id, original_filename, mime_type, content
	from invoice
	where slug = invoice_slug
	on conflict (invoice_id) do update
	set original_filename = excluded.original_filename
	  , mime_type = excluded.mime_type
	  , content = excluded.content
	;
$$
	language sql
;

revoke execute on function attach_to_invoice(uuid, text, text, bytea) from public;
grant execute on function attach_to_invoice(uuid, text, text, bytea) to invoicer;
grant execute on function attach_to_invoice(uuid, text, text, bytea) to admin;

commit;
