-- Deploy numerus:remove_collection to pg
-- requires: roles
-- requires: schema_numerus
-- requires: invoice_collection
-- requires: collection
-- requires: collection_attachment
-- requires: update_invoice_collection_status

begin;

set search_path to numerus, public;

create or replace function remove_collection(collection_slug uuid) returns void as
$$
declare
	cid integer;
	iid integer;
begin
	select collection_id into cid from collection where slug = collection_slug;
	if not found then
		return;
	end if;

	delete from invoice_collection where collection_id = cid returning invoice_id into iid;
	if iid is not null then
		perform update_invoice_collection_status(null, iid, 0);
	end if;

	delete from collection_attachment where collection_id = cid;
	delete from collection where collection_id = cid;
end
$$
	language plpgsql
;

revoke execute on function remove_collection(uuid) from public;
grant execute on function remove_collection(uuid) to invoicer;
grant execute on function remove_collection(uuid) to admin;

commit;
