import type { User } from "../domain/userEntity";
import * as actionTypes from "./userActionTypes";
import { getUser, updateUser } from "./userService";
import { dropAuth } from "auth/data/authActions";
import UnauthorizedHandler from "core/handlers/unauthorizedHandler";

// TODO: Make dispatch typing

const setUserAction = (user: User) => (dispatch: any) =>
  dispatch({ type: actionTypes.SET_USER, user });

const getUserAction =
  () =>
  (dispatch: any): Promise<User> => {
    dispatch({ type: actionTypes.GET_USER });

    return getUser()
      .then((user) => {
        dispatch({ type: actionTypes.GET_USER_SUCCESS, user });

        return user;
      })
      .catch((reason) => {
        const handler = new UnauthorizedHandler(() => dropAuth()(dispatch));
        handler.handle(reason);
        return reason;
      });
  };

const updateUserAction =
  (user: Partial<User>) =>
  (dispatch: any): Promise<void> => {
    dispatch({ type: actionTypes.UPDATE_USER });

    return updateUser(user)
      .then((user) => {
        dispatch({ type: actionTypes.UPDATE_USER_SUCCESS });

        return user;
      })
      .catch((reason) => {
        const handler = new UnauthorizedHandler(() => dropAuth()(dispatch));
        handler.handle(reason);
        throw reason;
      });
  };

export { setUserAction, getUserAction, updateUserAction };
