import { TextUtil } from "@greatness/util";
import { useCallback, useEffect } from "react";
import { useSearchParams } from "react-router-dom";

import removeQueryParameter from "./removeQueryParameter";
import useQueryParameter from "./useQueryParameter";
import JWTUtil, { AccessToken } from "./JWTUtil";

export default function useOAuthQueryToken(): {
  removeTokenFromQuery: () => void;
  setToken: (response: AccessToken) => void;
  token: string | null;
} {
  const token = useQueryParameter("token");
  const [, setSearchParams] = useSearchParams();

  useEffect(() => {
    if (!TextUtil.isEmpty(token)) {
      JWTUtil.set({ accessToken: token! });
    }
  }, [token]);

  const setToken = useCallback((response: AccessToken) => {
    JWTUtil.set(response);
  }, []);

  const removeTokenFromQuery = useCallback(() => {
    removeQueryParameter(setSearchParams, "token");
  }, [setSearchParams]);

  return { removeTokenFromQuery, setToken, token };
}
