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

begin;

select plan(15);

set search_path to auth, tipus, public;

select has_function('public', 'set_cookie', array ['text']);
select function_lang_is('public', 'set_cookie', array ['text'], 'sql');
select function_returns('public', 'set_cookie', array ['text'], 'void');
select isnt_definer('public', 'set_cookie', array ['text']);
select volatility_is('public', 'set_cookie', array ['text'], 'stable');
select function_privs_are('public', 'set_cookie', array ['text'], 'guest', array []::text[]);
select function_privs_are('public', 'set_cookie', array ['text'], 'publisher', array []::text[]);
select function_privs_are('public', 'set_cookie', array ['text'], 'admin', array []::text[]);
select function_privs_are('public', 'set_cookie', array ['text'], 'authenticator', array ['EXECUTE']);

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', 'publisher', '44facbb30d8a419dfd4bfbc44a4b5539d4970148dfc84bed0e',
        current_timestamp + interval '1 month')
     , (5, 'admin@tandem.blog', 'Demo', 'test', 'admin', '12af4c88b528c2ad4222e3740496ecbc58e76e26f087657524',
        current_timestamp + interval '1 month')
;

prepare user_info as
    select current_user_email(), current_user_cookie(), current_user;

select lives_ok(
               $$ select set_cookie('44facbb30d8a419dfd4bfbc44a4b5539d4970148dfc84bed0e/demo@tandem.blog') $$,
               'Should run ok for a valid cookie'
           );

select results_eq(
               'user_info',
               $$ values ('demo@tandem.blog', '44facbb30d8a419dfd4bfbc44a4b5539d4970148dfc84bed0e', 'publisher'::name) $$,
               'Should have updated the info with the correct user'
           );

reset role;

select lives_ok(
               $$ select set_cookie('12af4c88b528c2ad4222e3740496ecbc58e76e26f087657524/admin@tandem.blog') $$,
               'Should run ok for a different cookie'
           );

select results_eq(
               'user_info',
               $$ values ('admin@tandem.blog', '12af4c88b528c2ad4222e3740496ecbc58e76e26f087657524', 'admin'::name) $$,
               'Should have updated the info with the other user'
           );

reset role;

select lives_ok(
               $$ select set_cookie('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/admin@tandem.blog') $$,
               'Should run ok even for an invalid cookie'
           );

select results_eq(
               'user_info',
               $$ values ('', '', 'guest'::name) $$,
               'Should have updated the info as a guest user'
           );

reset role;

select *
from finish();

rollback;
