import { AccountApi } from '@openapi/idm';
import omit from 'lodash/omit';
import { ActionTree, GetterTree, MutationTree } from 'vuex';
import { State } from '@/types/store/scopes';

const accountApi = new AccountApi();

const countPending: Record<string, any> = {};
const countCache: Record<string, any> = {};
let lastOpts: string | null = '';

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

export const getters: GetterTree<State, State> = {
  accountsCard(state) {
    return state.card;
  },
  accountsLoading(state) {
    return state.loading;
  },
  accountsRecords(state) {
    return state.records;
  },
  accountsRowsNumber(state) {
    return state.rowsNumber;
  },
};

export const mutations: MutationTree<State> = {
  accountsCard(state, card) {
    state.card = card;
  },
  accountsLoading(state, loading) {
    state.loading = loading;
  },
  accountsRecords(state, records) {
    state.records = records;
  },
  accountsRowsNumber(state, rowsNumber) {
    state.rowsNumber = rowsNumber;
  },
};

export const actions: ActionTree<State, State> = {
  dispatchAccount({ commit }: any = {}, { id, data = {} }) {
    commit('accountsLoading', true);

    return accountApi
      .getAccount(id, data.expand)
      .then(({ data }) => {
        commit('accountsCard', data);

        return data;
      })
      .catch(() => {
        throw new Error('[store][idm][dispatchAccount]');
      })
      .finally(() => {
        commit('accountsLoading', false);
      });
  },
  dispatchAccounts({ commit }: any = {}, opts = {}) {
    commit('accountsLoading', true);

    lastOpts = JSON.stringify(omit(opts, 'perPage', 'page'));

    accountApi
      .pagingAccounts(
        opts.handler,
        opts.page,
        opts.perPage,
        opts.query,
        opts.fulltext,
        opts.sort,
        opts.expand,
        opts.options
      )
      .then(({ data }) => {
        commit('accountsRecords', data.records);

        if (lastOpts) {
          countCache[lastOpts] = Number(data.totalRows || 0);
          commit('accountsRowsNumber', countCache[lastOpts]);
        }

        return data.records;
      })
      .catch(() => {
        throw new Error('[store][idm][dispatchAccounts]');
      })
      .finally(() => {
        commit('accountsLoading', false);
      });

    if (typeof countCache[lastOpts] === 'number') {
      // @ts-ignore
      commit('accountsRowsNumber', countCache[lastOpts]);
    }
  },
  filterAccounts({ commit }: any = {}, opts = {}) {
    commit('accountsLoading', true);
    lastOpts = JSON.stringify(omit(opts, 'perPage', 'page'));

    accountApi
      .searchAccountsWithFilter(
        opts.page,
        opts.perPage,
        opts.fulltext,
        opts.org,
        opts.role,
        opts.expand,
        opts.options
      )
      .then(({ data }) => {
        commit('accountsRecords', data.records);

        if (lastOpts) {
          countCache[lastOpts] = Number(data.totalRows || 0);
          commit('accountsRowsNumber', countCache[lastOpts]);
        }
        return data.records;
      })
      .catch(() => {
        throw new Error('[store][idm][filterAccounts]');
      })
      .finally(() => {
        commit('accountsLoading', false);
      });
    if (typeof countCache[lastOpts] === 'number') {
      // @ts-ignore
      commit('accountsRowsNumber', countCache[lastOpts]);
    }
  },
};
