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

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

const gqlQuery = `
  query getAdServersPCN(
    $page: Int
    $pageSize: Int
    $sortBy: String
    $sortOrder: String
    $searchText: String
    $status: Int
    $placementId: Int
  ) {
    getAdServersPCN(
      page: $page
      pageSize: $pageSize
      sortBy: $sortBy
      sortOrder: $sortOrder
      searchText: $searchText
      status: $status
      placementId: $placementId
    ) {
      records {
        id
        name
        url
        placementId
        macro
        comments
        updatedBy
        updatedAt
        status
      }
      recordsTotal
    }
  }
`;

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

    return variables;
  },
  processResponse: ({ data: { getAdServersPCN } }) => ({
    records: getAdServersPCN.records,
    recordsTotal: getAdServersPCN.recordsTotal,
    allRecordsCount: getAdServersPCN.recordsTotal,
  }),
  setTableAction,
});
