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

const gqlQuery = `
  query getPlayers(
    $sortBy: String
    $sortOrder: String
    $page: Int
    $pageSize: Int
    $searchText: String
    $publisherId: Int
    $type: Int
  ) {
    getPlayers(
      sortBy: $sortBy
      sortOrder: $sortOrder
      page: $page
      pageSize: $pageSize
      searchText: $searchText
      publisherId: $publisherId
      type: $type
    ) {
      allRecordsCount
      records {
        id
        alias
        comments
      publisher {
        id
        name
      }
      type
        updatedBy
        updatedAt
        embedCode
      }
      recordsTotal
    }
  }
`;

export default createEpicGetData({
  gqlQuery,
  triggerActionType: getDataAction.type,
  processBodyRequest: (state) => {
    const type = playersSelectors.typeSelector(state);
    const publisher = playersSelectors.publisherSelector(state);

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

    if (type?.id) {
      variables.type = type.id;
    }

    if (publisher?.value) {
      variables.publisherId = publisher.value;
    }

    return variables;
  },
  processResponse: ({ data: { getPlayers } }) => getPlayers,
  setTableAction,
});
