import { STATUSES_ALL } from '../../constants';
import { GET_XRAY_CAMPAIGNS } from '@/graphql/services/xRayCampaings/constants';

import { PAYLOAD_GET_XRAY_CAMPAIGNS } from '@/graphql/services/xRayCampaings/types/payload/xRayCampaigns';

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

const gqlQuery = `
  query ${GET_XRAY_CAMPAIGNS}($payload: ${PAYLOAD_GET_XRAY_CAMPAIGNS}) {
    ${GET_XRAY_CAMPAIGNS}(payload: $payload) {
      records {
        id
        name
        publisherName
        advertisingBrandName
        xrayLineItems {
          xrayCampaignId
          status
          startTime
          endTime
        }
        status
        startTime
        endTime
        updatedBy
        updatedAt
      }
      recordsTotal
    }
  }
`;

export default createEpicGetData({
  gqlQuery,
  triggerActionType: getDataAction.type,
  processBodyRequest: (state) => {
    const status = selectors.statusSelector(state);
    const advertisingBrandId = selectors.advertiserSelector(state)?.id;
    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 (advertisingBrandId) {
      variables.advertisingBrandId = advertisingBrandId;
    }

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

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

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