import {
    ApiHandlerDiscreteParameter,
    createHandlerChainRunnerOptionalParameter,
    HasOnComplete,
} from "@insite/client-framework/HandlerCreator";
import { getSession, GetSessionApiParameter, Session } from "@insite/client-framework/Services/SessionService";

type HandlerType = ApiHandlerDiscreteParameter<
    GetSessionApiParameter & HasOnComplete<{ apiResult: Session }> & { isSessionUpdate?: true },
    GetSessionApiParameter,
    Session
>;

export const DispatchBeginLoadSession: HandlerType = props => {
    props.dispatch({
        type: "Context/BeginLoadSession",
        isSessionUpdate: props.parameter.isSessionUpdate,
    });
};

export const PopulateApiParameter: HandlerType = props => {
    const { onComplete, ...apiParameter } = props.parameter;
    props.apiParameter = apiParameter;
};

export const RequestDataFromApi: HandlerType = async props => {
    props.apiResult = await getSession(props.apiParameter);
};

export const DispatchCompleteLoadSession: HandlerType = props => {
    props.dispatch({
        type: "Context/CompleteLoadSession",
        session: props.apiResult,
    });
};

/** @deprecated Not needed anymore */
export const LoadCurrentBillTo: HandlerType = () => {};

/** @deprecated Not needed anymore */
export const LoadCurrentShipTo: HandlerType = () => {};

export const chain = [
    DispatchBeginLoadSession,
    PopulateApiParameter,
    RequestDataFromApi,
    DispatchCompleteLoadSession,
    LoadCurrentBillTo,
    LoadCurrentShipTo,
];

const loadSession = createHandlerChainRunnerOptionalParameter(chain, {}, "LoadSession");
export default loadSession;
