-- Deploy numerus:add_contact to pg
-- requires: schema_numerus
-- requires: extension_vat
-- requires: email
-- requires: extension_pg_libphonenumber
-- requires: extension_uri
-- requires: country_code
-- requires: contact
-- requires: tag_name
-- requires: tax_details
-- requires: contact_web
-- requires: contact_phone
-- requires: contact_tax_details
-- requires: contact_iban
-- requires: contact_bic

begin;

set search_path to numerus, public;

create or replace function add_contact(company_id integer, name text, phone text, email text, web text, tax_details tax_details, iban text, bic text, tags tag_name[]) returns uuid as
$$
declare
	cid integer;
	cslug uuid;
begin
	insert into contact (company_id, name, tags)
	values (add_contact.company_id, add_contact.name, add_contact.tags)
	returning contact_id, slug
	into cid, cslug
	;

	if tax_details is not null then
		insert into contact_tax_details (contact_id, business_name, vatin, address, city, province, postal_code, country_code)
		values (cid, tax_details.business_name, (tax_details.country_code || tax_details.vatin)::vatin, tax_details.address, tax_details.city, tax_details.province, tax_details.postal_code, tax_details.country_code)
		;
	end if;

	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(tax_details.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;

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

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

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


	return cslug;
end
$$
	language plpgsql
;

revoke execute on function add_contact(integer, text, text, text, text, tax_details, text, text, tag_name[]) from public;
grant execute on function add_contact(integer, text, text, text, text, tax_details, text, text, tag_name[]) to invoicer;
grant execute on function add_contact(integer, text, text, text, text, tax_details, text, text, tag_name[]) to admin;

drop function if exists add_contact(integer, text, text, text, text, email, uri, text, text, text, text, country_code, tag_name[]);

commit;
