import { STATUSES_ALL } from '../../constants';
import { GET_USERS } from '@/graphql/services/users/constants';

import { PAYLOAD_NAME } from '@/graphql/services/users/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_USERS}($payload: ${PAYLOAD_NAME}) {
    ${GET_USERS}(payload: $payload) {
      records {
        id
        email
        firstName
        lastName
        accountId
        departmentId
        status
        updateDate
        updatedBy
        lastLoginDate
        department {
          id
          name
        }
        role {
          name
          displayName
          type
          readOnlyInSelfServe
        }
        account {
          name
        }
      }
      recordsTotal
    }
  }
`;

export default createEpicGetData({
  gqlQuery,
  triggerActionType: getDataAction.type,
  processBodyRequest: (state) => {
    const status = selectors.statusSelector(state);
    const account = selectors.accountSelector(state);
    const role = selectors.roleSelector(state);
    const department = selectors.departmentSelector(state);

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

    if (role) {
      variables.roleId = role.value;
    }

    if (department) {
      variables.departmentId = department.value;
    }

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

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