import { GET_CONTENT_OWNERS } from '../../../../../graphql/services/contentOwners/constants';
import { STATUSES_ALL } from '../../constants';

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

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

const gqlQuery = `
  query ${GET_CONTENT_OWNERS}($payload: ${PAYLOAD_NAME}) {
    ${GET_CONTENT_OWNERS}(payload: $payload) {
      records {
        id
        name
        status
        type
        comments
        activeFeedsCount
        feedsCount
        salesforce_id
        call_to_action
        play_from_co
        isPublic
        update_date
        updated_by
      }
      recordsTotal
    }
  }
`;

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

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

    if (status !== STATUSES_ALL) {
      variables.status = status;
    }

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

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