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

const clientScopeApi = new ClientScopeApi();

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

export const getters: GetterTree<State, State> = {
  scopesCard(state) {
    return state.card;
  },
  scopesLoading(state) {
    return state.loading;
  },
  scopesRecords(state) {
    return state.records;
  },
  scopesRowsNumber(state) {
    return state.rowsNumber;
  },
};

export const mutations: MutationTree<State> = {
  scopesCard(state, card) {
    state.card = card;
  },
  scopesLoading(state, loading) {
    state.loading = loading;
  },
  scopesRecords(state, records: []) {
    state.records = records;
  },
  scopesRowsNumber(state, rowsNumber) {
    state.rowsNumber = rowsNumber;
  },
};

export const actions: ActionTree<State, State> = {
  dispatchScopes({ commit }: ActionContext<State, State>, opts = {}) {
    commit('scopesLoading', true);

    return clientScopeApi
      .pagingClientScopes(
        opts.page,
        opts.perPage,
        opts.query,
        opts.fulltext,
        opts.sort,
        opts.expand,
        opts.options
      )
      .then(({ data }) => {
        commit('scopesLoading', false);
        commit('scopesRowsNumber', data.totalRows);
        commit('scopesRecords', data.records);

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