import React from "react";
import { useEffect, useState } from "react";
import { FortressEntryProps } from "./types/type";
import isAuth from "./functions/is-auth";
import { useDispatch } from "react-redux";
import { setConfig } from "./redux/FortressConfigReducer";

/**
 * Renders the Fortress component.
 *
 * @param {FortressEntryProps} props - The props for the Fortress component.
 * @returns {JSX.Element} The rendered Fortress component.
 */
export const FortressApp = (props : FortressEntryProps ): JSX.Element => {
  const [auth, setAuth] = useState({ succeed: false, failed: true });
  const dispatch = useDispatch();
  const {config} = props

  useEffect(() => {
    if (auth.failed) {
      isAuth(config)
        .then((response) => {
          setAuth({ succeed: true, failed: false });
        })
        .catch((error) => {
          setAuth({ succeed: false, failed: true });
        });
    }
  }, [config, auth, setAuth]);

  // Set reducer global config
  useEffect(() => {
    dispatch(setConfig(config));
  }, [dispatch, config]);

  return <>{auth.succeed && props.children}</>;
};

export default FortressApp;
