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) return;
    getAccessToken(LOGTO_RESOURCE)
      .then(token => {
        if (token) {
          setHeaders({ Authorization: `Bearer ${token}` })
          return;
        }
        app.notification.warning({
          key: 'use-auth-headers-login-expired',
          title: '登陆已过期',
          actions: [
            <Button key='auto-signin' type="primary" onClick={() => autoSignIn() }>重新登陆</Button>
          ],
        });
      });
  }, [isAuthenticated]);
  return headers;
}