-- recordings table schema
CREATE TABLE api.recordings (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  url TEXT NOT NULL,
  created_at timestamp(6) without time zone,
  updated_at timestamp(6) without time zone,
  discord_message_id TEXT
);

-- roles & permissions for our backend automation user
GRANT all ON api.recordings TO automation;
GRANT SELECT ON api.recordings TO web_anon;


-- we re-create this function to use recording_id instead of vod_id
DROP FUNCTION public.tg__add_record_job CASCADE;
CREATE FUNCTION public.tg__add_record_job() RETURNS trigger
  LANGUAGE plpgsql SECURITY DEFINER
  SET search_path TO 'pg_catalog', 'public', 'pg_temp'
  AS $$
    begin
      PERFORM graphile_worker.add_job('record', json_build_object(
        'url', NEW.url,
        'recording_id', NEW.id
      ), max_attempts := 6);
      return NEW;
    end;
  $$;



CREATE TRIGGER create_recording
  AFTER UPDATE ON api.recordings
  FOR EACH ROW
  EXECUTE FUNCTION tg__add_record_job();
