import { isSameMindr } from '../../core-utils.mjs.js';
import { createLogger } from '../../logger.mjs.js';
import { ACTION__MINDR_CREATE_OR_UPDATE } from '../actions/actionTypes.mjs.js';

const logger = createLogger('modules/store/reducers/createOrUpdateMindr');

export const createOrUpdateMindrReducer = (state, action) => {
    const { type, payload } = action;
    if (type !== ACTION__MINDR_CREATE_OR_UPDATE) {
        return state;
    }

    const { mindr } = payload;
    const { mindrs: allMindrs, ...stateWithoutMindrs } = state;
    const mindrsWithoutUpdatedMindr = allMindrs.filter(
        item => !isSameMindr(item, mindr)
    );
    const mindrs = [...mindrsWithoutUpdatedMindr, mindr];

    const localState = {
        ...stateWithoutMindrs,
        mindrs
    };

    return localState;
};
