-- Test add_payment_account_card
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, public;

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

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


set client_min_messages to warning;
truncate payment_account_card 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_card(1, 'Card A', '1234', '2024-04-04') $$,
	'Should be able to insert a first card payment account'
);

select lives_ok (
	$$ select add_payment_account_card(1, 'Card 2', '2345', '2025-05-05') $$,
	'Should be able to insert a second card payment account'
);

select bag_eq(
	$$ select company_id, payment_account_type::text, name, last_four_digits, expiration_date::text from payment_account join payment_account_card using (payment_account_id, payment_account_type) $$,
	$$ values (1, 'card', 'Card A', '1234', '2024-04-04')
	        , (1, 'card', 'Card 2', '2345', '2025-05-05')
	$$,
	'Should have created all payment accounts'
);

select *
from finish();

rollback;
