import { GET_SSO_ITEMS } from '@/graphql/services/sso/constants';

import { PAYLOAD_GET_SSO_ITEMS } from '@/graphql/services/sso/types/payload/ssoList';

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

const gqlQuery = `
  query ${GET_SSO_ITEMS}($payload: ${PAYLOAD_GET_SSO_ITEMS}) {
    ${GET_SSO_ITEMS}(payload: $payload) {
      records {
        id
        displayName
        provider
        onlyExisting
        status
        updatedBy
        updatedAt
      }
      recordsTotal
    }
  }
`;

export default createEpicGetData({
  gqlQuery,
  triggerActionType: getDataAction.type,
  processBodyRequest: (state) => {
    const variables = {
      page: selectors.pageSelector(state),
      pageSize: selectors.pageSizeSelector(state),
      sortBy: selectors.sortBySelector(state),
      sortOrder: selectors.sortOrderSelector(state),
    };

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

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