import { ActionTree, GetterTree, MutationTree } from 'vuex';
import { Interagency, InteragencyApi } from '@openapi/registry-service';
import { notifyError } from '@/utils/notify';
import cloneDeep from 'lodash/cloneDeep';
import merge from 'lodash/merge';
import mzService from '@services/mz/index';

const interagencyApi = new InteragencyApi();

function timeout(ms: number) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

export const defaultInteragency = () => ({
  attachments: []
});

export const defaultChildInteragency = () => ({
  ...defaultInteragency(),
  mapping: {
    out: {},
  },
  formRequest: '',
  formResponse: ''
});

export const state = {
  parentInteragency: null as Interagency | null,
  childInteragency: null as Interagency | null,
  childTestResponse: null,
};

export type State = typeof state;

export const getters: GetterTree<State, State> = {
  getParentInteragency(state): Interagency | undefined | null {
    return state.parentInteragency;
  },
  getChildInteragency(state): Interagency | undefined | null {
    return state.childInteragency;
  },
  getChildTestResponse(state): any {
    return state.childTestResponse;
  },
};

export const mutations: MutationTree<State> = {
  setParentInteragency(state, interagency): void {
    state.parentInteragency = cloneDeep(interagency);
  },
  setChildInteragency(state, interagency): void {
    state.childInteragency = cloneDeep(interagency);
  },
  setChildTestResponse(state, data): void {
    state.childTestResponse = cloneDeep(data);
  },
};

export const actions: ActionTree<State, State> = {
  async getParentInteragencyById({ commit, getters }, id) {
    try {
      const { data } = await interagencyApi.getInteragency(
        id,
        'childrenInteragency,attachments'
      );
      const interagency = merge(defaultInteragency(), data);
      commit('setParentInteragency', interagency);
      return interagency;
    } catch (error) {
      if (error instanceof Error) {
        notifyError(error.message);
      }
    }
  },
  async getChildInteragencyById({ commit, getters }, id) {
    try {
      const { data } = await interagencyApi.getInteragency(
        id,
        'bpmnTemplate,attachments,formRequest,formResponse'
      );
      const interagency = merge(defaultChildInteragency(), data);
      commit('setChildInteragency', interagency);
      return interagency;
    } catch (error) {
      if (error instanceof Error) {
        notifyError(error.message);
      }
    }
  },
  async createChildInteragency({ commit, getters }, newInteragency) {
    try {
      const { data } = await interagencyApi.createInteragency([newInteragency]);
      if (data.success) {
        commit('setChildInteragency', newInteragency);
      }
      return data;
    } catch (error) {
      if (error instanceof Error) {
        notifyError(error.message);
      }
    }
  },
  async testChildRequest({ commit, getters }, data) {
    try {
      let response: any = await mzService.postGatewayRequest(data);
      const traceId = response?.data?.id;
      await timeout(40000);
      response = await mzService.getHistoryById(traceId);
      const content = JSON.parse(response.statusJson.content);
      if (content?.code === 'XsdValidationException') {
        commit('setChildTestResponse', content);
      } else {
        commit('setChildTestResponse', 'Запрос завершился успешно.');
      }
    } catch (e) {
      if (e instanceof Error) {
        commit('setChildTestResponse', e.message);
        notifyError(e.message);
      }
    }
  },
};
