create or replace function movie_showtime_expiry(
  id integer
) returns timestamp with time zone
security definer
language 'plpgsql' as $$
declare
  start_time timestamp with time zone;
begin
  select into start_time ms.start_time
    from movie_showtimes_with_current_and_sold_out_unmaterialized ms
  where id = id;
  if start_time < now() then
    return null;
  else
    if start_time > now() + '7 days'::interval then
      return start_time - '7 days'::interval;
    else
      return start_time;
    end if;
  end if;
end
$$;


