-- Deploy camper:media to pg
-- requires: roles
-- requires: schema_camper
-- requires: company
-- requires: media_content
-- requires: user_profile

begin;

set search_path to camper, public;

create table media (
	media_id integer generated by default as identity primary key,
	company_id integer not null references company,
	content_hash bytea not null references media_content,
	original_filename text not null constraint original_filename_not_empty check(length(trim(original_filename)) > 0)
);

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

alter table media enable row level security;

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

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

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

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

commit;
