// @ts-ignore
import { router } from '@router';
import { WorkflowServiceApi } from '@openapi/wf';
import { ActionTree, GetterTree, MutationTree } from 'vuex';

const wfApi = new WorkflowServiceApi();

interface State {
  waitTraceId: Set<string>;
}

export const state: State = {
  waitTraceId: new Set<string>(),
};

export const getters: GetterTree<State, State> = {
  waitTraceId(state) {
    return state.waitTraceId;
  },
  currentUserInfo(state, _, __, rootGetters) {
    const {
      //
      sub: userId,
      name: fullName,
      domain_id: orgId,
      realm: orgFullName,
    } = rootGetters['oidcClient/currentUser'] || {};
    // const [, orgFullName] = realm.match(/(.*)\./) || [];

    return {
      orgId,
      fullName,
      userId,
      orgFullName,
    };
  },
};

export const mutations: MutationTree<State> = {
  addToWaitTraceId(state, waitTraceId) {
    state.waitTraceId.add(waitTraceId);
  },
  removeWaitTraceId(state, traceId) {
    state.waitTraceId.delete(traceId);
  },
};

export const actions: ActionTree<State, State> = {
  async dispatchProcess(
    { commit, getters },
    {
      data = {},
      processKey,
      redirectUrl = router.currentRoute.fullPath, // ? src/components/statements/index.ts
    } = {}
  ) {
    const requestBody = {
      processKey,
      userId: getters.currentUserInfo.userId,
    };

    const {
      data: { traceId },
    } = await wfApi.start({
      ...requestBody,
      data: {
        redirectUrl,
        readonlyFields: [],
        currentUserInfo: getters.currentUserInfo,
        ...data,
      },
    });
    if (traceId) {
      commit('addToWaitTraceId', traceId);
    }
    return { traceId };
  },

  async submitForm(
    { commit, getters },
    {
      //
      formModel = {},
      taskId,
      traceId,
    }
  ) {
    const {
      data: { processFinished, wfValidationResult },
    } = await wfApi.submitForm(taskId, {
      ...formModel,
      currentUserInfo: getters.currentUserInfo,
    });

    if (!wfValidationResult) {
      throw new Error('В форму были переданы не верные значения');
    }

    // Подписываемся только если процесс не завершен
    if (!processFinished && traceId) {
      commit('addToWaitTraceId', traceId);
    }
    return { traceId };
  },
};
