import { STATUSES_ALL } from '../../constants';
import { GET_XRAY_CREATIVES } from '@/graphql/services/xRayCreatives/constants';

import { PAYLOAD_GET_XRAY_CREATIVES } from '@/graphql/services/xRayCreatives/types/payload/xRayCreatives';

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

const gqlQuery = `
  query ${GET_XRAY_CREATIVES}($payload: ${PAYLOAD_GET_XRAY_CREATIVES}) {
    ${GET_XRAY_CREATIVES}(payload: $payload) {
      records {
        id
        image
        title
        name
        publisherName
        updatedBy
        updatedAt
        status
      }
      recordsTotal
    }
  }
`;

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

    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 (publisherId) {
      variables.publisherId = publisherId;
    }

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

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