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

begin;

set search_path to numerus, auth, public;

select plan(15);

select has_function('numerus', 'current_user_cookie', array []::name[]);
select function_lang_is('numerus', 'current_user_cookie', array []::name[], 'sql');
select function_returns('numerus', 'current_user_cookie', array []::name[], 'text');
select isnt_definer('numerus', 'current_user_cookie', array []::name[]);
select volatility_is('numerus', 'current_user_cookie', array []::name[], 'stable');
select function_privs_are('numerus', 'current_user_cookie', array []::name[], 'guest', array ['EXECUTE']);
select function_privs_are('numerus', 'current_user_cookie', array []::name[], 'invoicer', array ['EXECUTE']);
select function_privs_are('numerus', 'current_user_cookie', array []::name[], 'admin', array ['EXECUTE']);
select function_privs_are('numerus', 'current_user_cookie', array []::name[], 'authenticator', array []::text []);

set client_min_messages to warning;
truncate auth."user" cascade;
reset client_min_messages;

insert into auth."user" (user_id, email, name, password, role, cookie, cookie_expires_at)
values (1, 'demo@tandem.blog', 'Demo', 'test', 'invoicer', '44facbb30d8a419dfd4bfbc44a4b5539d4970148dfc84bed0e', current_timestamp + interval '1 month')
     , (5, 'admin@tandem.blog', 'Demo', 'test', 'admin', '12af4c88b528c2ad4222e3740496ecbc58e76e26f087657524', current_timestamp + interval '1 month')
;

select lives_ok(
	$$ select set_cookie('44facbb30d8a419dfd4bfbc44a4b5539d4970148dfc84bed0e/demo@tandem.blog') $$,
	'Should change ok for the first user'
);

select is(current_user_cookie(), '44facbb30d8a419dfd4bfbc44a4b5539d4970148dfc84bed0e', 'Should return the cookie of the first user');

reset role;


select lives_ok(
	$$ select set_cookie('12af4c88b528c2ad4222e3740496ecbc58e76e26f087657524/admin@tandem.blog') $$,
	'Should change ok for the second user'
);

select is(current_user_cookie(), '12af4c88b528c2ad4222e3740496ecbc58e76e26f087657524', 'Should return the cookie of the second user');

reset role;

select lives_ok(
	$$ select set_cookie('') $$,
	'Should change ok for a guest user'
);

select is(current_user_cookie(), '', 'Should return an empty string');

reset role;

select *
from finish();

rollback;
