import {
    ApiHandlerDiscreteParameter,
    createHandlerChainRunner,
    HasOnSuccess,
} from "@insite/client-framework/HandlerCreator";
import { batchCreateVmiUsers, BatchCreateVmiUsersApiParameter } from "@insite/client-framework/Services/AccountService";
import { ServiceResult } from "@insite/client-framework/Services/ApiService";
import { VmiUserImportCollectionModel } from "@insite/client-framework/Types/ApiModels";

type HandlerType = ApiHandlerDiscreteParameter<
    BatchCreateVmiUsersApiParameter & HasOnSuccess<VmiUserImportCollectionModel>,
    BatchCreateVmiUsersApiParameter,
    ServiceResult<VmiUserImportCollectionModel>
>;

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

export const RequestDataFromApi: HandlerType = async props => {
    props.apiResult = await batchCreateVmiUsers(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/Accounts/Reset",
    });
};

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

const uploadVmiUsers = createHandlerChainRunner(chain, "UploadVmiUsers");
export default uploadVmiUsers;
