-- Deploy numerus:edit_contact to pg
-- requires: schema_numerus
-- requires: email
-- requires: extension_uri
-- requires: country_code
-- requires: tag_name
-- requires: contact
-- requires: extension_vat
-- requires: extension_pg_libphonenumber

begin;

set search_path to numerus, public;

create or replace function edit_contact(contact_slug uuid, business_name text, vatin text, trade_name text, phone text, email email, web uri, address text, city text, province text, postal_code text, country_code country_code, tags tag_name[]) returns uuid as
$$
declare
	cid integer;
	company integer;
begin
	update contact
	set business_name = edit_contact.business_name
	  , vatin = (edit_contact.country_code || edit_contact.vatin)::vatin
	  , trade_name = edit_contact.trade_name
	  , phone = parse_packed_phone_number( edit_contact.phone, edit_contact.country_code)
	  , email = edit_contact.email
	  , web = edit_contact.web
	  , address = edit_contact.address
	  , city = edit_contact.city
	  , province = edit_contact.province
	  , postal_code = edit_contact.postal_code
	  , country_code = edit_contact.country_code
	  , tags = edit_contact.tags
	where slug = contact_slug
	returning contact_id, company_id
	into cid, company
	;

	if cid is null then
		return null;
	end if;

	return contact_slug;
end
$$
	language plpgsql
;

revoke execute on function edit_contact(uuid, text, text, text, text, email, uri, text, text, text, text, country_code, tag_name[]) from public;
grant execute on function edit_contact(uuid, text, text, text, text, email, uri, text, text, text, text, country_code, tag_name[]) to invoicer;
grant execute on function edit_contact(uuid, text, text, text, text, email, uri, text, text, text, text, country_code, tag_name[]) to admin;

commit;
