-- Test add_payment_account_bank
set client_min_messages to warning;
create extension if not exists pgtap;
reset client_min_messages;

begin;

select plan(12);

set search_path to numerus, auth, public;

select has_function('numerus', 'add_payment_account_bank', array['integer', 'text', 'iban']);
select function_lang_is('numerus', 'add_payment_account_bank', array['integer', 'text', 'iban'], 'plpgsql');
select function_returns('numerus', 'add_payment_account_bank', array['integer', 'text', 'iban'], 'uuid');
select isnt_definer('numerus', 'add_payment_account_bank', array['integer', 'text', 'iban']);
select volatility_is('numerus', 'add_payment_account_bank', array['integer', 'text', 'iban'], 'volatile');

select function_privs_are('numerus', 'add_payment_account_bank', array['integer', 'text', 'iban'], 'guest', array []::text[]);
select function_privs_are('numerus', 'add_payment_account_bank', array['integer', 'text', 'iban'], 'invoicer', array ['EXECUTE']);
select function_privs_are('numerus', 'add_payment_account_bank', array['integer', 'text', 'iban'], 'admin', array ['EXECUTE']);
select function_privs_are('numerus', 'add_payment_account_bank', array['integer', 'text', 'iban'], 'authenticator', array []::text[]);


set client_min_messages to warning;
truncate payment_account_bank cascade;
truncate payment_account cascade;
truncate payment_method cascade;
truncate company cascade;
reset client_min_messages;

set constraints "company_default_payment_method_id_fkey" deferred;

insert into company (company_id, business_name, vatin, trade_name, phone, email, web, address, city, province, postal_code, country_code, currency_code, default_payment_method_id)
values (1, 'Company 2', 'XX123', '', '555-555-555', 'a@a', '', '', '', '', '', 'ES', 'EUR', 111)
     , (2, 'Company 4', 'XX234', '', '666-666-666', 'b@b', '', '', '', '', '', 'FR', 'USD', 222)
;

insert into payment_method (payment_method_id, company_id, name, instructions)
values (111, 1, 'cash', 'cash')
     , (222, 2, 'cash', 'cash')
;

set constraints "company_default_payment_method_id_fkey" immediate;

select lives_ok(
	$$ select add_payment_account_bank(1, 'Bank A', 'ES2820958297603648596978') $$,
	'Should be able to insert a first bank payment account'
);

select lives_ok (
	$$ select add_payment_account_bank(1, 'Bank 2', 'DE68500105178297336485') $$,
	'Should be able to insert a second bank payment account'
);

select bag_eq(
	$$ select company_id, payment_account_type::text, name, iban::text from payment_account join payment_account_bank using (payment_account_id, payment_account_type) $$,
	$$ values (1, 'bank', 'Bank A', 'ES2820958297603648596978')
	        , (1, 'bank', 'Bank 2', 'DE68500105178297336485')
	$$,
	'Should have created all payment accounts'
);


select *
from finish();

rollback;
