import { TYPE_ALL } from '../../constants';
import { GET_ROLE_LIST } from '@/graphql/services/rolesPermissions/constants';

import { PAYLOAD_GET_ROLE_LIST } from '@/graphql/services/rolesPermissions/types/payload/roleList';

import * as selectors from '../selectors';
import { getDataAction, setTableAction } from '../slices';
import createEpicGetData from '@/modules/@common/Table/redux/epics';

const gqlQuery = `
  query ${GET_ROLE_LIST}($payload: ${PAYLOAD_GET_ROLE_LIST}) {
    ${GET_ROLE_LIST}(payload: $payload) {
      records {
        id
        displayName
        type
        accountName
        updatedBy
        updatedAt
      }
      recordsTotal
    }
  }
`;

export default createEpicGetData({
  gqlQuery,
  triggerActionType: getDataAction.type,
  processBodyRequest: (state) => {
    const type = selectors.typeSelector(state);
    const accountId = selectors.accountSelector(state)?.id;

    const variables = {
      page: selectors.pageSelector(state),
      pageSize: selectors.pageSizeSelector(state),
      sortBy: selectors.sortBySelector(state),
      sortOrder: selectors.sortOrderSelector(state),
      searchText: selectors.searchSelector(state),
    };

    if (type !== TYPE_ALL) {
      variables.type = type;
    }

    if (accountId) {
      variables.accountId = accountId;
    }

    return {
      payload: variables,
    };
  },
  processResponse: ({ data }) => {
    const res = data[GET_ROLE_LIST];

    return {
      records: res.records,
      recordsTotal: res.recordsTotal,
      allRecordsCount: res.recordsTotal,
    };
  },
  setTableAction,
});
