import { ApiHandler, createHandlerChainRunner } from "@insite/client-framework/HandlerCreator";
import { getDealerByPath, GetDealerByPathApiParameter } from "@insite/client-framework/Services/DealerService";
import { DealerModel } from "@insite/client-framework/Types/ApiModels";

type HandlerType = ApiHandler<GetDealerByPathApiParameter, DealerModel>;

export const DispatchBeginLoadDealerByPath: HandlerType = props => {
    props.dispatch({
        type: "Data/Dealers/BeginLoadDealerByPath",
        path: props.parameter.path,
    });
};

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

export const RequestDataFromApi: HandlerType = async props => {
    try {
        props.apiResult = await getDealerByPath(props.apiParameter);
    } catch (error) {
        if (error?.status === 404 || error?.status === 400) {
            return;
        }
        throw error;
    }
};

export const DispatchCompleteLoadDealerByPath: HandlerType = props => {
    props.dispatch({
        type: "Data/Dealers/CompleteLoadDealerByPath",
        dealer: props.apiResult,
        path: props.parameter.path,
    });
};

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

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

export const chain = [
    DispatchBeginLoadDealerByPath,
    PopulateApiParameter,
    RequestDataFromApi,
    DispatchCompleteLoadDealerByPath,
    DispatchSetDealerId,
];

const loadDealerByPath = createHandlerChainRunner(chain, "LoadDealerByPath");
export default loadDealerByPath;
