import React from "react";
import type { AuthStore } from "auth/domain/authStore";

import type { AuthStoreState } from "./authReducer";
import { authenticateAction, authInitAction, dropAuth } from "./authActions";
import { RootState, useAppDispatch, useAppSelector } from "store";

const authSelector = (state: RootState): AuthStoreState => state.auth;

const useAuthStore = (): AuthStore => {
  const { isFailed, isLoading, isLogedIn } = useAppSelector(authSelector);

  const dispatch = useAppDispatch();

  const authenticate = React.useCallback(
    (code: string) => authenticateAction(code)(dispatch),
    [dispatch]
  );

  const init = React.useCallback(() => authInitAction()(dispatch), [dispatch]);

  const signOut = React.useCallback(() => dropAuth()(dispatch), [dispatch]);

  return {
    isLogedIn,
    isFailed,
    isLoading,
    authenticate,
    signOut,
    init,
  };
};

export { useAuthStore };
