import {
    ApiHandlerDiscreteParameter,
    createHandlerChainRunner,
    HasOnSuccess,
} from "@insite/client-framework/HandlerCreator";
import { ServiceResult } from "@insite/client-framework/Services/ApiService";
import {
    batchCreateVmiLocations,
    BatchCreateVmiLocationsApiParameter,
} from "@insite/client-framework/Services/VmiLocationService";
import { VmiLocationCollectionModel } from "@insite/client-framework/Types/ApiModels";

type HandlerType = ApiHandlerDiscreteParameter<
    BatchCreateVmiLocationsApiParameter & HasOnSuccess<VmiLocationCollectionModel>,
    BatchCreateVmiLocationsApiParameter,
    ServiceResult<VmiLocationCollectionModel>
>;

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

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

export const ExecuteOnSuccessCallback: HandlerType = props => {
    if (props.apiResult.successful) {
        props.parameter.onSuccess?.(props.apiResult.result);
    }
};

export const DispatchClearDataView: HandlerType = props => {
    props.dispatch({
        type: "Data/VmiLocations/Reset",
    });
};

export const chain = [PopulateApiParameter, RequestDataFromApi, ExecuteOnSuccessCallback, DispatchClearDataView];

const uploadVmiLocations = createHandlerChainRunner(chain, "UploadVmiLocations");
export default uploadVmiLocations;
