-- Deploy camper:contact to pg
-- requires: roles
-- requires: schema_camper
-- requires: user_profile
-- requires: company
-- requires: id_document_type
-- requires: country_code
-- requires: country

begin;

set search_path to camper, public;

create table contact (
	contact_id integer generated by default as identity primary key,
	company_id integer not null references company,
	slug uuid not null unique default gen_random_uuid(),
	name text not null constraint name_not_empty check(length(trim(name)) > 1),
	id_document_type_id varchar(1) not null references id_document_type,
	id_document_number text 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,
	created_at timestamptz not null default current_timestamp
);

grant select, insert, update, delete on table contact to employee;
grant select, insert, update, delete on table contact to admin;

alter table contact enable row level security;

create policy company_policy
on contact
using (
	exists(
		select 1
		from company_user
		join user_profile using (user_id)
		where company_user.company_id = contact.company_id
	)
);

commit;
