-- Deploy camper:setup_redsys to pg
-- requires: roles
-- requires: schema_camper
-- requires: redsys
-- requires: redsys_environment
-- requires: redsys_integration

begin;

set search_path to camper, public;

create or replace function setup_redsys(company integer, merchant_code text, terminal_number integer, environment redsys_environment, integration redsys_integration, encrypt_key text) returns void as
$$
begin
	if encrypt_key is null then
		update redsys
		set merchant_code = setup_redsys.merchant_code,
		    terminal_number = setup_redsys.terminal_number,
		    environment = setup_redsys.environment,
		    integration = setup_redsys.integration
		where company_id = company
		;
	else
		insert into redsys (company_id, merchant_code, terminal_number, environment, integration, encrypt_key)
		values (company, merchant_code, terminal_number, environment, integration, decode(encrypt_key, 'base64'))
		on conflict (company_id) do update
		set merchant_code = excluded.merchant_code,
		    terminal_number = excluded.terminal_number,
		    environment = excluded.environment,
		    integration = excluded.integration,
		    encrypt_key = decode(setup_redsys.encrypt_key, 'base64')
		;
	end if;
end
$$
	language plpgsql
;

revoke execute on function setup_redsys(integer, text, integer, redsys_environment, redsys_integration, text) from public;
grant execute on function setup_redsys(integer, text, integer, redsys_environment, redsys_integration, text) to admin;

commit;