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

begin;

set search_path to camper, public;

create or replace function edit_media(media_id integer, filename text, media_type media_type default null, content bytea default null) returns integer as
$$
declare
	hash bytea;
begin
	if content is not null then
		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
		;
	end if;

	update media
	set original_filename = filename
	  , content_hash = coalesce(hash, content_hash)
	where media.media_id = edit_media.media_id
	;

	return media_id;
end
$$
language plpgsql
;

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

commit;
