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

import { RESET_PASSWORD } from '@/graphql/services/users/constants';
import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

import { PAYLOAD_NAME } from '@/graphql/services/users/types/payload/resetPassword';

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

const query = `
  mutation ${RESET_PASSWORD}($payload: ${PAYLOAD_NAME}) {
    ${RESET_PASSWORD}(payload: $payload){
      email
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(resetPasswordAction.type),
    switchMap((action) => {
      const stream$ = gqlRequest({
        query,
        variables: {
          payload: {
            email: action.payload,
          },
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            return of(
              notifyAction({
                type: TYPE_SUCCESS,
                message: 'Password reset successfully',
              }),
            );
          }

          return EMPTY;
        }),
      );

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