import isApiError from "@insite/client-framework/Common/isApiError";
import {
    ApiHandlerDiscreteParameter,
    createHandlerChainRunner,
    executeAwaitableHandlerChain,
    HasOnError,
    HasOnSuccess,
} from "@insite/client-framework/HandlerCreator";
import { updateAccount, UpdateAccountApiParameter } from "@insite/client-framework/Services/AccountService";
import loadCurrentAccount from "@insite/client-framework/Store/Data/Accounts/Handlers/LoadCurrentAccount";
import { AccountModel } from "@insite/client-framework/Types/ApiModels";

type HandlerType = ApiHandlerDiscreteParameter<
    { account: AccountModel } & HasOnSuccess & HasOnError<string>,
    UpdateAccountApiParameter,
    AccountModel
>;

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

export const CallUpdateAccount: HandlerType = async props => {
    try {
        props.apiResult = await updateAccount(props.apiParameter);
    } catch (error) {
        if (isApiError(error) && error.status === 400) {
            props.parameter.onError?.(error.errorJson.message);
            return false;
        }
        throw error;
    }
};

export const LoadCurrentAccount: HandlerType = async props => {
    await executeAwaitableHandlerChain(loadCurrentAccount, {}, props);
};

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

export const chain = [PopulateApiParameter, CallUpdateAccount, LoadCurrentAccount, ExecuteOnSuccessCallback];

const updateCurrentAccount = createHandlerChainRunner(chain, "UpdateCurrentAccount");
export default updateCurrentAccount;
