import { ActionType, isActionOf } from "typesafe-actions";
import { Epic } from "redux-observable";
import { from, of, Observable } from "rxjs";
import { push } from "connected-react-router";
import { switchMap, filter, map, catchError } from "rxjs/operators";
import "../../app/bootstrap";
import * as actions from "../actions/authActions";

type Action = ActionType<typeof actions>;
type Params = {
  payload: {
    email: string;
    password: string;
  };
};

export const submitSignUpFormEpic: Epic = (
  action$: Observable<Action>,
  undefined,
  { user }
) =>
  action$.pipe(
    filter(isActionOf(actions.submitSignUpForm)),
    switchMap(({ payload }: Params) => {
      return from(user.signUp(payload.email, payload.password)).pipe(
        map((user) => {
          if (user) {
            return push("/welcome");
          }
        }),
        catchError((error: Error) => of(actions.submitSignUpFormFailure(error)))
      );
    })
  );

export default submitSignUpFormEpic;