import { useLogto } from "@logto/react"
import { useEffect, useState } from "react";
import { LOGTO_RESOURCE } from "../utils/constants";
import { App, Button } from "antd";
import useAutoLogin from "./useAutoLogin";

export const useAuthHeaders = (): HeadersInit | undefined => {
  const { isAuthenticated, getAccessToken } = useLogto();
  const [headers, setHeaders] = useState<HeadersInit | undefined>();
  const { autoSignIn } = useAutoLogin();
  const app = App.useApp();
  useEffect(() => {
    if (isAuthenticated) {
      getAccessToken(LOGTO_RESOURCE).then(token => {
        if (!token) {
          app.notification.warning({
            key: 'use-auth-headers-login-expired',
            title: '登陆已过期',
            actions: [
              <Button onClick={() => autoSignIn() }>重新登陆</Button>
            ]
          })
          return;
        }
        setHeaders({ Authorization: `Bearer ${token}` })
      });
    }
  }, [isAuthenticated]);
  return headers;
}