import { STATUSES_ALL } from '../../constants';
import { GET_LIST } from '@/graphql/services/customReports/constants';

import { PAYLOAD_NAME } from '@/graphql/services/customReports/types/payload/list';

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

const gqlQuery = `
  query ${GET_LIST}($payload: ${PAYLOAD_NAME}) {
    ${GET_LIST}(payload: $payload) {
      rows {
        id
        account {
          id
          name
        }
        uiName
        enabled
        icon
        description
        lookerReportId
        allSites
        publisherIds
        updatedAt
        updatedBy
        createdAt
        createdBy
      }
      countTotal
    }
  }
`;

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

    // todo: check flow
    if (status !== STATUSES_ALL) {
      variables.enabled = !!status;
    }

    if (account) {
      variables.accountId = account.value;
    }

    return {
      payload: variables,
    };
  },
  processResponse: ({ data }) => ({
    records: data[GET_LIST].rows,
    recordsTotal: data[GET_LIST].countTotal,
    allRecordsCount: data[GET_LIST].countTotal,
  }),
  setTableAction,
});
