-- Deploy camper:set_season_range to pg
-- requires: roles
-- requires: schema_camper
-- requires: season_calendar
-- requires: unset_season_range

begin;

set search_path to camper, public;

create or replace function set_season_range(szn_id integer, range daterange) returns void as
$$
declare
	tmp_range daterange;
begin
	select daterange(min(lower(season_range)), max(upper(season_range)))
	into tmp_range
	from season_calendar
	where season_id = szn_id
	and (season_range && range or season_range -|- range)
	;
	if not lower_inf(tmp_range) and not upper_inf(tmp_range) then
		range := range + tmp_range;
	end if;

	perform unset_season_range(range);

	insert into season_calendar (season_id, season_range)
	values (szn_id, range);
end
$$
	language plpgsql
;

revoke execute on function set_season_range(integer, daterange) from public;
grant execute on function set_season_range(integer, daterange) to admin;

commit;