import {
    ApiHandlerDiscreteParameter,
    createHandlerChainRunner,
    HasOnSuccess,
} from "@insite/client-framework/HandlerCreator";
import { ServiceResult } from "@insite/client-framework/Services/ApiService";
import {
    GetWishListLinesApiParameter,
    PdfBarcodeDataFieldOptions,
    sendPdf,
    SendWishListPdfApiParameter,
} from "@insite/client-framework/Services/WishListService";
import { PdfBarcodeFormatOptions, PdfLayoutOptions } from "@insite/client-framework/Types/PrintPdfModels";

interface Parameter extends HasOnSuccess {
    lineIds?: string[];
    layout: PdfLayoutOptions;
    barcodeFormat: PdfBarcodeFormatOptions;
    barcodeField: PdfBarcodeDataFieldOptions;
    displayFields?: string[];
    addOverlay?: boolean;
    baseParameter: GetWishListLinesApiParameter;
}

type HandlerType = ApiHandlerDiscreteParameter<Parameter, SendWishListPdfApiParameter, ServiceResult<{}>>;

export const CreateParameter: HandlerType = props => {
    props.apiParameter = {
        ...props.parameter.baseParameter,
        lineIds: props.parameter.lineIds,
        layout: props.parameter.layout,
        barcodeFormat: props.parameter.barcodeFormat,
        barcodeField: props.parameter.barcodeField,
        displayFields: props.parameter.displayFields,
        addOverlay: props.parameter.addOverlay,
    };
};

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

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

export const chain = [CreateParameter, CallApi, ExecuteOnSuccessCallback];

const sendWishListPdf = createHandlerChainRunner(chain, "SendWishListPdf");
export default sendWishListPdf;
