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

begin;

set search_path to camper, public;

create table media (
	media_id serial not null primary key,
	company_id integer not null references company,
	hash bytea not null generated always as (sha256(content)) stored,
	original_filename text not null constraint original_filename_not_empty check(length(trim(original_filename)) > 0),
	media_type media_type not null,
	content bytea not null,
	unique (company_id, hash)
);

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

grant usage on sequence media_media_id_seq 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;