import { STATUSES_ALL } from '../../constants';
import { GET_XRAY_LINE_ITEMS } from '@/graphql/services/xRayLineItems/constants';

import { PAYLOAD_GET_XRAY_LINE_ITEMS } from '@/graphql/services/xRayLineItems/types/payload/xRayLineItemsList';

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

const gqlQuery = `
  query ${GET_XRAY_LINE_ITEMS}($payload: ${PAYLOAD_GET_XRAY_LINE_ITEMS}) {
    ${GET_XRAY_LINE_ITEMS}(payload: $payload) {
      records {
        id
        name
        publisherName
        rate
        status
        startTime
        endTime
        updatedBy
        updatedAt
      }
      recordsTotal
    }
  }
`;

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

    const queryParams = new URLSearchParams(window.location.search);
    const xrayCampaignId = +queryParams.get('xrayCampaignId');

    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;
    }

    if (xrayCampaignId) {
      variables.xrayCampaignId = xrayCampaignId;
    }

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

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