import { UserTask, WorkflowServiceApi } from '@openapi/wf';
import { ActionTree, GetterTree, MutationTree } from 'vuex';

const wfApi = new WorkflowServiceApi();

interface State {
  count: number;
  currentTask: UserTask | null;
}

export const state: State = {
  count: 0,
  currentTask: null,
};

export const getters: GetterTree<State, State> = {
  count(state) {
    return state.count;
  },
  currentTask(state) {
    return state.currentTask;
  },
};

export const mutations: MutationTree<State> = {
  count(state, count) {
    state.count = count;
  },
  currentTask(state, task: UserTask) {
    state.currentTask = task;
  },
};

export const actions: ActionTree<State, State> = {
  dispatchCountTasks({ commit }: any = {}) {
    return wfApi.taskList().then(({ data: { totalCount = 0 } }) => {
      commit('count', totalCount);
    });
  },
  async fetchUserData(
    { commit, getters },
    businessKey: string
  ): Promise<UserTask | null> {
    if (!businessKey) return null;
    const assignee = getters['oidcClient/currentUser'].sub;
    const {
      data: { tasks = [] },
    } = await wfApi.findUserTasks(businessKey, undefined, assignee);
    const userTask = tasks[0]?.userTask || null;
    commit('currentTask', userTask);
    return userTask;
  },
};
