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

import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

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

const query = `
  mutation SendTestEmail(
    $email: String!,
  ) {
    sendTestEmail(
      email: $email 
    ) {
       email
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(sendTestEmailAction.type),
    switchMap((action) => {
      const stream$ = gqlRequest({
        query,
        variables: {
          email: action.payload,
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            return of(
              notifyAction({
                type: TYPE_SUCCESS,
                message: `Successfully sent email ${action.payload}`,
              }),
            );
          }

          return EMPTY;
        }),
      );

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