-- Deploy camper:amenity_feature to pg
-- requires: roles
-- requires: schema_camper
-- requires: amenity
-- requires: icon
-- requires: user_profile

begin;

set search_path to camper, public;

create table amenity_feature (
	amenity_feature_id integer generated by default as identity primary key,
	amenity_id integer not null references amenity,
	icon_name text not null references icon,
	name text not null constraint name_not_empty check(length(trim(name)) > 0),
	position integer not null default 2147483647
);

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

alter table amenity_feature enable row level security;

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

create policy insert_to_company
on amenity_feature
for insert
with check (
	exists (select 1 from amenity join user_profile using (company_id) where amenity.amenity_id = amenity_feature.amenity_id)
)
;

create policy update_company
on amenity_feature
for update
using (
	exists (select 1 from amenity join user_profile using (company_id) where amenity.amenity_id = amenity_feature.amenity_id)
)
;

create policy delete_from_company
on amenity_feature
for delete
using (
	exists (select 1 from amenity join user_profile using (company_id) where amenity.amenity_id = amenity_feature.amenity_id)
)
;

commit;
