import { createLogger } from '../../logger.mjs.js';
import {
    ACTION__MINDR_CREATE_OR_UPDATE,
    ACTION__MINDR_CREATE_OR_UPDATE_DRAFT
} from '../actions/actionTypes.mjs.js';

const logger = createLogger('reducers/createOrUpdateDraft');

export const createOrUpdateDraftReducer = (
    /** @type {MailmindrState} */ state,
    action
) => {
    const { type, payload } = action;
    if (type !== ACTION__MINDR_CREATE_OR_UPDATE_DRAFT) {
        return state;
    }

    const { mindr, sender } = payload;
    const { __drafts: drafts, ...stateWithoutMindrs } = state;
    const mindrsWithoutUpdatedMindr = (drafts || []).filter(
        item =>
            item.sender.id !== sender.id &&
            item.sender.windowId !== sender.windowId
    );
    const updatedDrafts = [...mindrsWithoutUpdatedMindr, payload];

    const localState = {
        ...stateWithoutMindrs,
        __drafts: updatedDrafts
    };

    return localState;
};
