-- Deploy camper:add_media to pg
-- requires: roles
-- requires: schema_camper
-- requires: media
-- requires: media_content
-- requires: media_type

begin;

set search_path to camper, public;

create or replace function add_media(company integer, filename text, media_type media_type, content bytea) returns integer as
$$
declare
	hash bytea;
	mid integer;
begin
	insert into media_content (media_type, bytes)
	values (media_type, content)
	on conflict (content_hash) do update
	set media_type = excluded.media_type
	returning content_hash into hash
	;

	insert into media (company_id, original_filename, content_hash)
	values (company, filename, hash)
	returning media_id into mid
	;

	return mid;
end
$$
	language plpgsql
;

revoke execute on function add_media(integer, text, media_type, bytea) from public;
grant execute on function add_media(integer, text, media_type, bytea) to admin;

commit;
