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

const solutionApi = new SolutionApi();

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

export const getters: GetterTree<State, State> = {
  solutionsCard(state) {
    return state.card;
  },
  solutionsLoading(state) {
    return state.loading;
  },
  solutionsRecords(state) {
    return state.records;
  },
  solutionsRowsNumber(state) {
    return state.rowsNumber;
  },
};

export const mutations: MutationTree<State> = {
  solutionsCard(state, card: Record<string, any> | null) {
    state.card = card;
  },
  solutionsLoading(state, loading: boolean) {
    state.loading = loading;
  },
  solutionsRecords(state, records: []) {
    state.records = records;
  },
  solutionsRowsNumber(state, rowsNumber: number) {
    state.rowsNumber = rowsNumber;
  },
};

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

    return solutionApi
      .getSolutionsPaging(
        opts.page,
        opts.perPage,
        opts.query,
        opts.fulltext,
        opts.sort,
        opts.expand,
        opts.options
      )
      .then(({ data }) => {
        commit('solutionsRowsNumber', data.totalRows);
        commit('solutionsRecords', data.records);

        return data;
      })
      .finally(() => {
        commit('solutionsLoading', false);
      })
      .catch(() => {
        throw new Error('[store][modules][idm][solutions][dispatchSolutions]');
      });
  },
};
