-- set_last_scanning_results updates the timestamp and errors of the last scan.
create or replace function set_last_scanning_results(
    p_repository_id uuid,
    p_last_scanning_errors text,
    p_scanning_errors_event_enabled boolean
)
returns void as $$
declare
    v_last_scanning_errors text := nullif(p_last_scanning_errors, '');
    v_prev_last_scanning_errors text;
begin
    -- Register repository scanning errors event if needed
    if p_scanning_errors_event_enabled and v_last_scanning_errors is not null then
        select last_scanning_errors into v_prev_last_scanning_errors
        from repository
        where repository_id = p_repository_id;

        if v_prev_last_scanning_errors is null or v_last_scanning_errors <> v_prev_last_scanning_errors then
            insert into event (repository_id, event_kind_id) values (p_repository_id, 4);
        end if;
    end if;

    -- Update repository with last scanning results
    update repository set
		last_scanning_ts = current_timestamp,
		last_scanning_errors = v_last_scanning_errors
	where repository_id = p_repository_id;
end
$$ language plpgsql;
