import { useEffect } from "react";
import { onMessage } from "firebase/messaging";
import { App } from "antd";
import type { NotificationData } from "../types";
import { getFirebaseApp, getFirebaseMessaging } from "../utils/firebase-frontend";

export const useFirebaseNotificationProcessor = () => {
  const { notification } = App.useApp();
  useEffect(() => {
    const app = getFirebaseApp();
    const messaging = getFirebaseMessaging();
    if (!app || !messaging) return;
    const unsubscribe = onMessage(messaging, async (payload) => {
      const data = payload.data as NotificationData;
      notification.success({
        title: data.title,
        description: data.body,
        icon: data.icon,
        onClick: () => {
          if (!data.url) return;
          open(data.url, '_blank'); // 打开通知
        },
      }); 
    });

    return () => unsubscribe(); // 组件卸载时取消监听
  }, []);
}