-- Deploy camper:amenity_carousel to pg
-- requires: roles
-- requires: schema_camper
-- requires: amenity
-- requires: media
-- requires: user_profile

begin;

set search_path to camper, public;

create table amenity_carousel (
	amenity_id integer not null references amenity,
	media_id integer not null references media,
	caption text not null,
	position integer not null default 2147483647,
	primary key (amenity_id, media_id)
);

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

alter table amenity_carousel enable row level security;

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

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

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

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

commit;
