/**
 * WordPress dependencies
 */
import { keyedReducer } from '@wordpress/data';

/**
 * Internal dependencies
 */
import type { Notice, ReducerAction } from './types';

/**
 * Reducer returning the next notices state. The notices state is an object
 * where each key is a context, its value an array of notice objects.
 *
 * @param state  Current state.
 * @param action Dispatched action.
 *
 * @return Updated state.
 */
const notices = keyedReducer< Array< Notice >, ReducerAction >( 'context' )( (
	state = [],
	action
) => {
	switch ( action.type ) {
		case 'CREATE_NOTICE':
			// Avoid duplicates on ID.
			return [
				...state.filter( ( { id } ) => id !== action.notice.id ),
				action.notice,
			];

		case 'REMOVE_NOTICE':
			return state.filter( ( { id } ) => id !== action.id );

		case 'REMOVE_NOTICES':
			return state.filter( ( { id } ) => ! action.ids.includes( id ) );

		case 'REMOVE_ALL_NOTICES':
			return state.filter( ( { type } ) => type !== action.noticeType );

		default:
			return state;
	}
} );

export default notices;
