-- Deploy numerus:payment_account_card to pg
-- requires: roles
-- requires: schema_numerus
-- requires: payment_account

begin;

set search_path to numerus, public;

create table payment_account_card (
	payment_account_id integer primary key,
	payment_account_type text not null default 'card' constraint payment_account_type_is_card check (payment_account_type = 'card'),
	last_four_digits text not null constraint last_four_digits_are_digits check ( last_four_digits ~ '^\d{4}$'),
	expiration_date date not null,
	foreign key (payment_account_id, payment_account_type) references payment_account (payment_account_id, payment_account_type)
);

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

alter table payment_account_card enable row level security;

create policy company_policy
on payment_account_card
using (
	exists(
		select 1
		from payment_account
		where payment_account.payment_account_id = payment_account_card.payment_account_id
	)
);

commit;
