import type { CTAHistory, } from '../types/CTAHistory'; import type { CTAState, } from '../types/CTAState'; import type { DefaultActionsRecord, } from '../types/DefaultActionsRecord'; import type { DispatchParameterTypes, } from '../types/DispatchParameterTypes'; import type { UseCTAParameterCreateFunc, UseCTAParameterCreateFuncReturnRecord, } from '../types/UseCTAParameterCreateFunc'; import type { Dispatch, UseCTAReturnTypeDispatch, } from '../types/UseCTAReturnTypeDispatch'; import ctaReducer from './ctaReducer'; export default function createDispatchInterface< Initial extends CTAState, Actions, FR extends UseCTAParameterCreateFuncReturnRecord, ReturnValue, >( dispatch: Dispatch, history: CTAHistory, createFunc: UseCTAParameterCreateFunc, actions?: Actions, ): UseCTAReturnTypeDispatch { const cta = { replace: payload => dispatch( { payload, type: 'replace', } as DispatchParameterTypes, ), replaceInitial: payload => dispatch( { payload, type: 'replaceInitial', } as DispatchParameterTypes, ), reset: payload => dispatch( { payload, type: 'reset', } as DispatchParameterTypes, ), update( payload: unknown, value: unknown, ) { if ( typeof payload === 'number' || typeof payload === 'string' ) { return dispatch( { payload: { [ payload ]: value, }, type: 'update', } as DispatchParameterTypes, ); } return dispatch( { payload, type: 'update', } as DispatchParameterTypes, ); }, updateInitial( payload: unknown, value: unknown, ) { if ( typeof payload === 'number' || typeof payload === 'string' ) { return dispatch( { payload: { [ payload ]: value, }, type: 'updateInitial', } as DispatchParameterTypes, ); } return dispatch( { payload, type: 'updateInitial', } as DispatchParameterTypes, ); }, } as UseCTAReturnTypeDispatch['cta']; const dispatchWrapper = Object.assign( dispatch, { cta, history, }, ); if ( actions && typeof actions === 'object' ) { const customActions = {} as Record< Exclude, keyof DefaultActionsRecord>, ( ...args: unknown[] ) => ReturnValue >; for ( const type in actions ) { if ( !( type in cta ) && typeof actions[ type ] === 'function' ) { customActions[ type as unknown as keyof typeof customActions ] = ( payload, ...args ) => dispatch( { payload, type, args, } as Parameters>[0]['nextCTAProps'], ); } } Object.assign( dispatchWrapper.cta, customActions, ); } return Object.assign( dispatchWrapper, { func: createFunc( dispatchWrapper, ), }, ); }