import { useMainStore } from '@/store';
import submitType from '@/constants/submit-type';

/*
    Encapsulates asynchronous Save Session logic inside a promise to allow for Save Session queuing
*/
async function saveSessionHelper(store, { submitAfterSave, createWorkOrderNumberForPIA }) {
    const savedSessionInfo = await store.saveSession({ submitAfterSave, createWorkOrderNumberForPIA });
    if (savedSessionInfo) {
        store.setSaveSessionInfo(savedSessionInfo.data);
    }
}

/*
    Will call API to save existing order, or create new one depending where it's called from.
    This will also set Referral information in the store after saving, and then
    update the cookie. To force synchronous behavior pass in 'true' for shouldAwaitSaveSessionQueue
*/
export async function saveSession({ shouldAwaitSaveSessionQueue = false, submitAfterSave = false, createWorkOrderNumberForPIA = false }) {
    const store = useMainStore();
    const saveSessionPromise = store.applicationUser.saveSessionPromise
        ? store.applicationUser.saveSessionPromise.then(() => saveSessionHelper(store, { submitAfterSave, createWorkOrderNumberForPIA }))
        : saveSessionHelper(store, { submitAfterSave, createWorkOrderNumberForPIA });

    store.setSaveSessionPromise(saveSessionPromise);

    if (!store.applicationUser.savedSessionId || shouldAwaitSaveSessionQueue) {
        await saveSessionPromise;
    }
}

/*
    Will determine if to submitWorkOrder.
    TODO: Add more description to this
*/
export async function submitWorkOrder({ submitType }) {
    const store = useMainStore();
    store.resetSubmittedOrder();
    await saveSession({
        shouldAwaitSaveSessionQueue: true,
        submitAfterSave: true
    });
    await store.createSubmittedOrder(submitType);
}

export async function submitBailout() {
    const store = useMainStore();
    store.resetSubmittedOrder();
    await store.saveSession({});
    await store.createSubmittedOrder(submitType.BAILOUT);
}
