import { STATUSES_ALL } from '../../constants';

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

const gqlQuery = `
  query GetHubs(
    $sortBy: String
    $sortOrder: String
    $page: Int
    $pageSize: Int
    $searchText: String
    $accountId: Int
    $status: Int
    $searchIn: [String]
  ) {
    getHubs(
      sortBy: $sortBy
      sortOrder: $sortOrder
      page: $page
      pageSize: $pageSize
      searchText: $searchText
      accountId: $accountId
      status: $status
      searchIn: $searchIn
    ) {
      records {
        id
        name
        accountName
        players {
          id
          publisherId
        }
        updatedAt
        updatedBy
      }
      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 variables;
  },
  processResponse: ({ data: { getHubs } }) => getHubs,
  setTableAction,
});
