import createReducer from 'bitbucket/internal/bbui/utils/create-reducer';
import { LOAD_REPOSITORIES_SUCCESS } from '../actions';

export default createReducer({}, {
    /**
     * On successful load of a page of repositories merge the data into an object keyed by repository id. This will
     * update properties if the repository already exists in the state.
     *
     * @param {Object} state
     * @param {Object} action
     * @param {Object} action.payload - a page of repositories, this will merge provided data with repositories in already in state
     * @returns {Object}
     */
    [LOAD_REPOSITORIES_SUCCESS](state, action) {
        const repos = action.payload.values.reduce((memo, repo) => {
            if (state.hasOwnProperty(repo.id)) {
                memo[repo.id] = {
                    ...state[repo.id],
                    ...repo,
                };
            } else {
                memo[repo.id] = repo;
            }

            return memo;
        }, {});

        return {...state, ...repos};
    },
});