import { DealerModel } from "@insite/client-framework/Types/ApiModels";
import {
    ApiHandlerDiscreteParameter,
    createHandlerChainRunner,
    HasOnError,
} from "@insite/client-framework/HandlerCreator";
import { GetDealerApiParameter, GetDealerByPathApiParameter } from "@insite/client-framework/Services/DealerService";
import loadDealer from "@insite/client-framework/Store/Data/Dealers/Handlers/LoadDealer";
import loadDealerByPath from "@insite/client-framework/Store/Data/Dealers/Handlers/LoadDealerByPath";

type HandlerType = ApiHandlerDiscreteParameter<
    {
        dealerPath: string;
        dealerId?: string;
    } & HasOnError,
    GetDealerApiParameter | GetDealerByPathApiParameter,
    DealerModel
>;

export const PopulateApiParameter: HandlerType = props => {
    const { dealerId, dealerPath } = props.parameter;

    props.apiParameter = dealerId
        ? ({ id: dealerId } as GetDealerApiParameter)
        : ({ path: dealerPath } as GetDealerByPathApiParameter);
};

export const DispatchSetDealerId: HandlerType = props => {
    if (!props.parameter.dealerId) {
        return;
    }

    props.dispatch({
        type: "Pages/SavedOrderDetails/SetDealerId",
        dealerId: props.parameter.dealerId,
    });
};

export const DispatchLoadDealer: HandlerType = props => {
    if ("id" in props.apiParameter) {
        props.dispatch(loadDealer(props.apiParameter));
    } else if ("path" in props.apiParameter) {
        props.dispatch(loadDealerByPath(props.apiParameter));
    }
};

export const chain = [PopulateApiParameter, DispatchSetDealerId, DispatchLoadDealer];

const ensureDealerLoaded = createHandlerChainRunner(chain, "EnsureDealerLoaded");
export default ensureDealerLoaded;
