CREATE or replace PROCEDURE vehiclepositions_data_retention(inout numberOfRows int, in dataRetentionMinutes int)
LANGUAGE plpgsql
AS $procedure$
	declare
		idsForDelete varchar(255)[];
	begin
        select array_agg(t.id) from pid.vehiclepositions_trips t
        left join pid.vehiclepositions_positions p on
            p.id = t.last_position_id
        where
            p.valid_to < (NOW() - (dataRetentionMinutes || ' minutes')::interval)
            or (gtfs_trip_id is null and p.created_at < NOW() - (dataRetentionMinutes || ' minutes')::interval) -- entries with valid to is null
        into idsForDelete;

        INSERT INTO pid.vehiclepositions_trips_history
        select * from pid.vehiclepositions_trips where id = ANY(idsForDelete)
        on conflict do nothing;

        INSERT INTO pid.vehiclepositions_positions_history
        select * from pid.vehiclepositions_positions where trips_id = ANY(idsForDelete)
        on conflict do nothing;

        delete from pid.vehiclepositions_positions where trips_id = ANY(idsForDelete);
        delete from pid.vehiclepositions_trips where id = ANY(idsForDelete);

        select array_length(idsForDelete,1) into numberOfRows;
	end;
$procedure$;

drop view v_vehiclepositions_past_stop_times;
drop table vehiclepositions_stop_times_history;

alter table vehiclepositions_trips drop column gtfs_direction_id;
alter table vehiclepositions_trips_history drop column gtfs_direction_id;

alter table ropidgtfs_precomputed_trip_schedule drop column direction_id;
