import { ofType } from 'redux-observable';
import { concat, EMPTY, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';

import { CHANGE_SSO_STATUS } from '@/graphql/services/sso/constants';
import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

import { PAYLOAD_NAME } from '@/graphql/services/sso/types/payload/status';

import { getDataAction, statusAction } from '../slices';
import { notifyAction } from '@/modules/@common/notify/redux/slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  mutation ${CHANGE_SSO_STATUS} ($payload: ${PAYLOAD_NAME}) {
    ${CHANGE_SSO_STATUS}(payload: $payload) {
      status
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(statusAction.type),
    switchMap((action) => {
      const { ids, status } = action.payload;
      const stream$ = gqlRequest({
        query,
        variables: {
          payload: { ids, status },
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            return concat(
              of(
                notifyAction({
                  type: TYPE_SUCCESS,
                  message: 'The Profile Status has been updated',
                }),
              ),
              of(getDataAction()),
            );
          }

          return EMPTY;
        }),
      );

      return concat(stream$);
    }),
  );
