import { createLogger } from '../../logger.mjs.js';
import { ACTION__MINDR_REMOVE } from '../actions/actionTypes.mjs.js';

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

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

    const { guid } = payload;
    const {
        mindrs: stateMindrs,
        overdue: stateOverdue,
        active: stateActive
    } = state;

    const mindrCount = {
        mindrs: (stateMindrs || []).length,
        overdue: (stateOverdue || []).length,
        active: (stateActive || []).length
    };

    logger.log(`mindr to be removed: ${guid}`, { guid, mindrCount });

    // 
    const mindrs = stateMindrs.filter(item => item.guid !== guid);

    const overdue = (stateOverdue || []).filter(mindr => mindr.guid !== guid);
    const active = (stateActive || []).filter(mindr => mindr.guid !== guid);

    if (
        mindrCount.overdue === overdue.length &&
        mindrCount.active === active.length &&
        mindrCount.mindrs === mindrs.length
    ) {
        // 
        logger.log(`no mindr was removed, state remains untouched`);

        return state;
    }

    const localState = {
        ...state,
        mindrs,
        active,
        overdue
    };

    return localState;
};
