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

begin;

select plan(14);

set search_path to auth, camper, public;

select has_function('camper', 'ensure_role_exists', array []::name[]);
select function_lang_is('camper', 'ensure_role_exists', array []::name[], 'plpgsql');
select function_returns('camper', 'ensure_role_exists', array []::name[], 'trigger');
select isnt_definer('camper', 'ensure_role_exists', array []::name[]);
select volatility_is('camper', 'ensure_role_exists', array []::name[], 'volatile');
select function_privs_are('camper', 'ensure_role_exists', array []::name[], 'guest', array []::text[]);
select function_privs_are('camper', 'ensure_role_exists', array []::name[], 'employee', array []::text[]);
select function_privs_are('camper', 'ensure_role_exists', array []::name[], 'admin', array []::text[]);
select function_privs_are('camper', 'ensure_role_exists', array []::name[], 'authenticator', array []::text[]);

select trigger_is('company_user', 'ensure_role_exists', 'ensure_role_exists');

set client_min_messages to warning;
truncate company_user cascade;
truncate company cascade;
truncate "user" cascade;
reset client_min_messages;

insert into auth."user" (user_id, email, name, password)
values (1, 'demo@tandem.blog', 'Demo', 'test')
     , (9, 'admin@tandem.blog', 'Demo', 'test')
;

insert into company (company_id, business_name, vatin, trade_name, phone, email, web, address, city, province, postal_code, rtc_number, tourist_tax, tourist_tax_max_days, country_code, currency_code, default_lang_tag)
values (2, 'Company 2', 'XX123', '', '555-555-555', 'a@a', '', '', '', '', '', '', 60, 7, 'ES', 'EUR', 'ca')
;

select lives_ok(
	$$ insert into company_user (company_id, user_id, role) values (2, 1, 'guest') $$,
	'Should be able to insert a user with a valid role'
);

select throws_ok(
	$$ insert into company_user (companY_id, user_id, role) values (2, 9, 'non-existing-role') $$,
	'23503',
	'role not found: non-existing-role',
	'Should not allow insert users with invalid roles'
);

select lives_ok($$ update company_user set role = 'employee' where company_id = 2 and user_id = 1 $$,
	'Should be able to change the role of a user to another valid role'
);

select throws_ok($$ update company_user set role = 'usurer' where company_id = 2 and user_id = 1 $$,
	'23503',
	'role not found: usurer',
	'Should not allow update users to invalid roles'
);


select *
from finish();

rollback;
