import { STATUSES_ALL } from '../../constants';
import { GET_INVITATIONS } from '@/graphql/services/invitations/constants';

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

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

const gqlQuery = `
  query ${GET_INVITATIONS}($payload: ${PAYLOAD_NAME}) {
    ${GET_INVITATIONS}(payload: $payload) {
      records {
        id
        email
        invitedById
        accountId
        url
        videoId
        createdAt
        updatedAt
        invStatus
        invitedByFullName
        videoData {
          videoName
          videoId
        }
        accountName
      }
      recordsTotal
    }
  }
`;

export default createEpicGetData({
  gqlQuery,
  triggerActionType: getDataAction.type,
  processBodyRequest: (state) => {
    const status = selectors.statusSelector(state);
    const account = selectors.accountSelector(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;
    }

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

    return {
      payload: variables,
    };
  },
  processResponse: ({ data }) => ({
    records: data[GET_INVITATIONS].records,
    recordsTotal: data[GET_INVITATIONS].recordsTotal,
    allRecordsCount: data[GET_INVITATIONS].recordsTotal,
  }),
  setTableAction,
});
