-- Deploy camper:redsys to pg
-- requires: roles
-- requires: schema_camper
-- requires: company
-- requires: redsys_environment
-- requires: redsys_integration
-- requires: user_profile

begin;

set search_path to camper, public;

create table redsys (
	company_id integer primary key references company,
	merchant_code text not null constraint merchant_code_valid check (merchant_code ~ '^\d{9}$'),
	terminal_number integer not null constraint terminal_number_in_range check(terminal_number > 0 and terminal_number < 1000),
	environment redsys_environment not null,
	integration redsys_integration not null,
	encrypt_key bytea not null
);

grant select (company_id, merchant_code, terminal_number, environment, integration) on table redsys to guest;
grant select (company_id, merchant_code, terminal_number, environment, integration) on table redsys to employee;
grant select (company_id, merchant_code, terminal_number, environment, integration) on table redsys to admin;
grant update (company_id, merchant_code, terminal_number, environment, integration, encrypt_key) on table redsys to admin;
grant insert (company_id, merchant_code, terminal_number, environment, integration, encrypt_key) on table redsys to admin;
grant delete on table redsys to admin;

alter table redsys enable row level security;

create policy guest_ok
on redsys
for select
using (true)
;

create policy insert_to_company
on redsys
for insert
with check (
	company_id in (select company_id from user_profile)
)
;

create policy update_company
on redsys
for update
using (
	company_id in (select company_id from user_profile)
)
;

create policy delete_from_company
on redsys
for delete
using (
	company_id in (select company_id from user_profile)
)
;

commit;