-- Deploy numerus:edit_collection to pg
-- requires: roles
-- requires: schema_numerus
-- requires: collection
-- requires: invoice_collection
-- requires: currency
-- requires: parse_price
-- requires: tag_name
-- requires: update_invoice_collection_status

begin;

set search_path to numerus, public;

create or replace function edit_collection(collection_slug uuid, collection_date date, payment_account_id integer, description text, amount text, tags tag_name[]) returns uuid as
$$
declare
	cid integer;
	iid integer;
	amount_cents integer;
begin
	update collection
	set collection_date = edit_collection.collection_date
	  , payment_account_id = edit_collection.payment_account_id
	  , description = edit_collection.description
	  , amount = parse_price(edit_collection.amount, decimal_digits)
	  , tags = edit_collection.tags
	from currency
	where slug = collection_slug
	  and currency.currency_code = collection.currency_code
	returning collection_id, collection.amount
	into cid, amount_cents
	;

	select invoice_id into iid
	from invoice_collection
	where collection_id = cid;

	if iid is not null then
		perform update_invoice_collection_status(cid, iid, amount_cents);
	end if;

	return collection_slug;
end
$$
	language plpgsql
;

revoke execute on function edit_collection(uuid, date, integer, text, text, tag_name[]) from public;
grant execute on function edit_collection(uuid, date, integer, text, text, tag_name[]) to invoicer;
grant execute on function edit_collection(uuid, date, integer, text, text, tag_name[]) to admin;

commit;
