-- Deploy numerus:edit_payment_account_card to pg
-- requires: roles
-- requires: schema_numerus
-- requires: payment_account
-- requires: payment_account_card
-- requires: extension_pgcrypto

begin;

set search_path to numerus, public;

create or replace function edit_payment_account_card(account_slug uuid, new_name text, new_last_digits text, new_exp_date date) returns uuid as
$$
declare
	account_id integer;
begin
	update payment_account
	set name = new_name
	where slug = account_slug
	  and payment_account_type = 'card'
	returning payment_account_id into account_id
	;
	
	if account_id is null then
		return null;
	end if;

	update payment_account_card
	set last_four_digits = new_last_digits
	  , expiration_date = new_exp_date
	where payment_account_id = account_id
	;

	return account_slug;
end
$$
	language plpgsql
;

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

commit;
