import { AnyAction } from "@reduxjs/toolkit";
import { AuthStore } from "auth/domain/authStore";
import * as actionTypes from "./authActionTypes";

type AuthStoreState = Omit<AuthStore, "authenticate" | "init" | "signOut">;

const INITIAL_STATE: AuthStoreState = {
  isFailed: false,
  isLoading: true,
  isLogedIn: false,
};

const authReducer = (
  state: AuthStoreState = INITIAL_STATE,
  action: AnyAction
): AuthStoreState => {
  switch (action.type) {
    case actionTypes.AUTH_LOGIN_REFRESH:
    case actionTypes.AUTH_LOGIN:
      return { ...state, isLoading: true };
    case actionTypes.AUTH_LOGIN_COMPLETE:
      return { ...state, isLoading: false, isFailed: false, isLogedIn: true };
    case actionTypes.AUTH_LOGIN_FAILED:
      return { ...state, isLoading: false, isFailed: true, isLogedIn: false };
    case actionTypes.DROP_AUTH:
      return { ...state, isLoading: false, isFailed: false, isLogedIn: false };
    default:
      return state;
  }
};

export { authReducer };
export type { AuthStoreState };
