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

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

import { resetPasswordEventAction } from '../slices';
import { setFormLoadingAction } from '@/modules/auth/common/redux/slices';
import { showNotificationAction } from '@/modules/layout/redux/slices';

export default (action$) =>
  action$.pipe(
    ofType(resetPasswordEventAction.type),
    switchMap(({ payload }) => {
      const stream$ = ajax({
        method: 'POST',
        url: `${process.env.APP_PCN_API_BASE_URL_FE}/public/auth/request-password-reset`,
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          email: payload.email,
        }),
      }).pipe(
        switchMap(() => concat(of(setFormLoadingAction(false)))),
        catchError(({ response }) =>
          concat(
            of(
              showNotificationAction({
                type: TYPE_ERROR,
                message: response?.message ?? 'Connection error',
              }),
            ),
            of(setFormLoadingAction(false)),
          ),
        ),
      );

      return concat(of(setFormLoadingAction(true)), stream$);
    }),
  );
