import { GET_ADVERTISERS } from '../../../../../graphql/services/advertisers/constants';

import { PAYLOAD_NAME } from '../../../../../graphql/services/advertisers/types/payload/advertisers';

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

const gqlQuery = `
  query ${GET_ADVERTISERS}($payload: ${PAYLOAD_NAME}) {
    ${GET_ADVERTISERS}(payload: $payload) {
      records {
        id
        name
        accountName
        salesforceId
        updatedBy
        updatedAt
      }
      recordsTotal
    }
  }
`;

export default createEpicGetData({
  gqlQuery,
  triggerActionType: getDataAction.type,
  processBodyRequest: (state) => {
    const variables = {
      page: selectors.pageSelector(state),
      pageSize: selectors.pageSizeSelector(state),
      sortBy: selectors.sortBySelector(state),
      sortOrder: selectors.sortOrderSelector(state),
      searchText: selectors.searchSelector(state),
    };

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

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