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

begin;

select plan(13);

set search_path to camper, public;

select has_function('camper', 'translate_location', array['integer', 'text', 'text', 'text']);
select function_lang_is('camper', 'translate_location', array['integer', 'text', 'text', 'text'], 'sql');
select function_returns('camper', 'translate_location', array['integer', 'text', 'text', 'text'], 'void');
select isnt_definer('camper', 'translate_location', array['integer', 'text', 'text', 'text']);
select volatility_is('camper', 'translate_location', array['integer', 'text', 'text', 'text'], 'volatile');
select function_privs_are('camper', 'translate_location', array['integer', 'text', 'text', 'text'], 'guest', array[]::text[]);
select function_privs_are('camper', 'translate_location', array['integer', 'text', 'text', 'text'], 'employee', array[]::text[]);
select function_privs_are('camper', 'translate_location', array['integer', 'text', 'text', 'text'], 'admin', array['EXECUTE']);
select function_privs_are('camper', 'translate_location', array['integer', 'text', 'text', 'text'], 'authenticator', array[]::text[]);


set client_min_messages to warning;
truncate location_i18n cascade;
truncate location cascade;
truncate company cascade;
reset client_min_messages;

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')
     , (4, 'Company 4', 'XX234', '', '666-666-666', 'b@b', '', '', '', '', '', '', 60, 7, 'FR', 'USD', 'ca')
;

insert into location (company_id, directions, map_embed, opening_dates)
values (2, '<p>Up</p>', '<map/>', '<p>Tomorrow</p>')
     , (4, '<p>Left</p>', '<map/>', '<p>Today</p>')
;

insert into location_i18n (company_id, lang_tag, directions, opening_dates)
values (2, 'ca', '<p>Uh?</p>', '<p>Uh?</p>')
     , (4, 'ca', '<p>Uh?</p>', '<p>Uh?</p>')
;

select lives_ok(
	$$ select translate_location(2, 'es', '<p>Arriba</p>', '<p>Mañana</p>') $$,
	'Should be able to translate the location of the first company to a new language'
);

select lives_ok(
	$$ select translate_location(2, 'ca', '<p>Dalt</p>', '<p>Demà</p>') $$,
	'Should be able to overwrite a location’s translation'
);

select lives_ok(
	$$ select translate_location(4, 'ca', null, null) $$,
	'Should be able to “translate” a location to empty strings'
);


select bag_eq(
	$$ select company_id, lang_tag, directions::text, opening_dates::text from location_i18n $$,
	$$ values (2, 'ca', '<p>Dalt</p>', '<p>Demà</p>')
	        , (2, 'es', '<p>Arriba</p>', '<p>Mañana</p>')
	        , (4, 'ca', '', '')
	$$,
	'Should have translated all locations'
);

select *
from finish();

rollback;
