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

begin;

select plan(14);

set search_path to camper, public;

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


set client_min_messages to warning;
truncate amenity 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 (1, 'Company 2', 'XX123', '', '555-555-555', 'a@a', '', '', '', '', '', '', 60, 7, 'ES', 'EUR', 'ca')
     , (2, 'Company 4', 'XX234', '', '666-666-666', 'b@b', '', '', '', '', '', '', 60, 7, 'FR', 'USD', 'ca')
;

select lives_ok(
	$$ select add_amenity(1, 'A1', 'Amenity A1', '<p>A1.1</p>', '<p>A1.2</p>') $$,
	'Should be able to add a amenity to the first company'
);

select lives_ok(
	$$ select add_amenity(1, 'B1', 'Amenity B1', '<p>B1.1</p>', '<p>B1.2</p>') $$,
	'Should be able to add a amenity to the same company, but with a different label'
);

select lives_ok(
	$$ select add_amenity(2, 'C1', 'Amenity C1', '<p>C1.1</p>', '<p>C1.2</p>') $$,
	'Should be able to add a amenity to the second company'
);

select throws_ok(
	$$ select add_amenity(3, 'C2', 'Amenity C2', '', '') $$,
	'23503', 'insert or update on table "amenity" violates foreign key constraint "amenity_company_id_fkey"',
	'Should raise an error if the company is not valid.'
);

select bag_eq(
	$$ select company_id, label, name, info1::text, info2::text, active from amenity $$,
	$$ values (1, 'A1', 'Amenity A1', '<p>A1.1</p>', '<p>A1.2</p>', true)
	        , (1, 'B1', 'Amenity B1', '<p>B1.1</p>', '<p>B1.2</p>', true)
	        , (2, 'C1', 'Amenity C1', '<p>C1.1</p>', '<p>C1.2</p>', true)
	$$,
	'Should have added all amenities'
);

select *
from finish();

select *
from finish();

rollback;
