-- Deploy numerus:contact_tax_details to pg
-- requires: roles
-- requires: schema_numerus
-- requires: contact
-- requires: extension_vat
-- requires: country_code
-- requires: country

begin;

set search_path to numerus, public;

create table contact_tax_details (
	contact_id integer primary key references contact,
	business_name text not null constraint business_name_not_empty check(length(trim(business_name)) > 1),
	vatin vatin not null,
	address text not null,
	city text not null,
	province text not null,
	postal_code text not null,
	country_code country_code not null references country
);

alter table contact_tax_details enable row level security;

create policy company_policy
on contact_tax_details
using (
	exists(
		select 1
		from contact
		where contact.contact_id = contact_tax_details.contact_id
	)
);

grant select, insert, update, delete on table contact_tax_details to invoicer;
grant select, insert, update, delete on table contact_tax_details to admin;

insert into contact_tax_details
select contact_id, business_name, vatin, address, city, province, postal_code, country_code
from contact;

update contact set trade_name = business_name where trade_name = '';

alter table contact
  rename column trade_name to name
;

alter table contact
  drop column business_name
, drop column vatin
, drop column address
, drop column city
, drop column province
, drop column postal_code
, drop column country_code
, add constraint name_not_empty check(length(trim(name)) > 1)
;

commit;