-- Deploy camper:add_contact to pg
-- requires: roles
-- requires: schema_camper
-- requires: email
-- requires: extension_pg_libphonenumber
-- requires: country_code
-- requires: contact
-- requires: contact_phone
-- requires: contact_email

begin;

set search_path to camper, public;

create or replace function add_contact(company_id integer, name text, id_document_type_id text, id_document_number text, phone text, email text, address text, city text, province text, postal_code text, country_code country_code) returns uuid as
$$
declare
	cid integer;
	cslug uuid;
begin
	insert into contact (company_id, name, id_document_type_id, id_document_number, address, city, province, postal_code, country_code)
	values (company_id, name, id_document_type_id, id_document_number, address, city, province, postal_code, country_code)
	returning contact_id, slug
	into cid, cslug
	;

	if phone is not null and trim(phone) <> '' then
		insert into contact_phone (contact_id, phone)
		values (cid, parse_packed_phone_number(add_contact.phone, coalesce(country_code, 'ES')))
		;
	end if;

	if email is not null and trim(email) <> '' then
		insert into contact_email (contact_id, email)
		values (cid, add_contact.email)
		;
	end if;

	return cslug;
end
$$
	language plpgsql
;

revoke execute on function add_contact(integer, text, text, text, text, text, text, text, text, text, country_code) from public;
grant execute on function add_contact(integer, text, text, text, text, text, text, text, text, text, country_code) to employee;
grant execute on function add_contact(integer, text, text, text, text, text, text, text, text, text, country_code) to admin;

commit;
