import { ACCOUNT_TYPE_ALL } from '../../constants';
import { GET_ACCOUNTS } from '@/graphql/services/accounts/constants';

import { PAYLOAD_NAME } from '@/graphql/services/accounts/types/payload/accounts';

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

const gqlQuery = `
  query ${GET_ACCOUNTS}($payload: ${PAYLOAD_NAME}) {
    ${GET_ACCOUNTS}(payload: $payload) {
      records {
        id
        name
        avatarUrl
        salesforceId
        type
        sitesAmount
        contentOwners {
          id
          name
        }
        updatedBy
        updatedAt
      }
      recordsTotal
    }
  }
`;

export default createEpicGetData({
  gqlQuery,
  triggerActionType: getDataAction.type,
  processBodyRequest: (state) => {
    const accountType = selectors.accountTypeSelector(state);

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

    if (accountType !== ACCOUNT_TYPE_ALL) {
      variables.type = accountType;
    }

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

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