import { ResourceApi } from '@openapi/idm';
import { ActionContext, ActionTree, GetterTree, MutationTree } from 'vuex';
import { State } from '@/types/store/scopes';

const resourceApi = new ResourceApi();

export const state: State = {
  card: {},
  loading: false,
  records: [],
  rowsNumber: 0,
};

export const getters: GetterTree<State, State> = {
  resourcesCard(state) {
    return state.card;
  },
  resourcesLoading(state) {
    return state.loading;
  },
  resourcesRecords(state) {
    return state.records;
  },
  resourcesRowsNumber(state) {
    return state.rowsNumber;
  },
};

export const mutations: MutationTree<State> = {
  resourcesCard(state, card) {
    state.card = card;
  },
  resourcesLoading(state, loading) {
    state.loading = loading;
  },
  resourcesRecords(state, records) {
    state.records = records;
  },
  resourcesRowsNumber(state, rowsNumber) {
    state.rowsNumber = rowsNumber;
  },
};

export const actions: ActionTree<State, State> = {
  dispatchResource(
    { commit }: ActionContext<State, State>,
    id,
    opts: Record<string, any> = {}
  ) {
    commit('resourcesLoading', true);

    return resourceApi
      .getResourceById(id, opts.expand)
      .then(({ data }) => {
        commit('resourcesLoading', false);
        commit('resourcesCard', data);

        return data;
      })
      .catch(() => {
        throw new Error('[store][modules][idm][recources][dispatchResource]');
      });
  },

  dispatchResources({ commit }, opts = {}) {
    commit('resourcesLoading', false);

    return resourceApi
      .getResourcesList(
        opts.page,
        opts.perPage,
        opts.query,
        opts.fulltext,
        opts.sort,
        opts.expand,
        opts.options
      )
      .then(({ data }) => {
        commit('resourcesLoading', false);
        commit('resourcesRowsNumber', data.totalRows);
        commit('resourcesRecords', data.records);

        return data;
      })
      .catch(() => {
        throw new Error('[store][modules][idm][recources][getResourcesList]');
      });
  },
};
