-- builds table schema
CREATE TABLE api.builds (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  vod UUID NOT NULL REFERENCES api.vods(id),
  task TEXT NOT NULL,
  created_at timestamp(6) without time zone,
  updated_at timestamp(6) without time zone
);

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


-- trigger function for starting the appropriate task when a new api.builds row is added
CREATE FUNCTION public.tg__add_build_job() RETURNS trigger
  LANGUAGE plpgsql SECURITY DEFINER
  SET search_path TO 'pg_catalog', 'public', 'pg_temp'
  AS $$
    begin
      PERFORM graphile_worker.add_job(NEW.task, json_build_object(
        'vod', NEW.vod
      ), max_attempts := 6);
      return NEW;
    end;
  $$;



CREATE TRIGGER create_build
  AFTER UPDATE ON api.builds
  FOR EACH ROW
  EXECUTE FUNCTION tg__add_build_job();
