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

const wfApi = new WorkflowServiceApi();

interface State {
  userTask: UserTask | null;
  taskProcess: TaskProcess | null;
}

export const state: State = {
  userTask: null,
  taskProcess: null,
};

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

export const mutations: MutationTree<State> = {
  saveTask(state, task: UserTaskListItem) {
    state.userTask = task?.userTask || null;
    state.taskProcess = task?.process || null;
  },
};

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