// useRealtimeNotifications：实时通知 Hook（P5）
// 依据：02-architecture-design.md §5 实时推送
// - WebSocket 接收 NotificationRequested 事件
// - 收到新通知时更新 urql 缓存（触发 NotificationFeed 重新渲染）
// - 收到 GradeRecorded / SchoolAnnouncement 事件时触发相应页面刷新

"use client";

import { useCallback } from "react";
import { useWebSocket } from "./useWebSocket";
import type { WebSocketEvent } from "@/types";

export function useRealtimeNotifications() {
  const handleEvent = useCallback((event: WebSocketEvent) => {
    switch (event.type) {
      case "NotificationRequested":
        // 新通知：触发 NotificationFeed 刷新
        // urql 会自动重新请求（staleTime 到期或手动 invalidate）
        // 这里通过 dispatchEvent 通知 NotificationFeed 组件
        window.dispatchEvent(
          new CustomEvent("realtime-notification", {
            detail: event.notification,
          }),
        );
        break;

      case "GradeRecorded":
        // 成绩发布：触发成绩页面刷新
        window.dispatchEvent(
          new CustomEvent("realtime-grade", {
            detail: {
              childId: event.childId,
              examId: event.examId,
            },
          }),
        );
        break;

      case "SchoolAnnouncement":
        // 学校公告：显示全局通知
        window.dispatchEvent(
          new CustomEvent("realtime-announcement", {
            detail: { title: event.title, body: event.body },
          }),
        );
        break;

      case "ChildBound":
        // 子女绑定：刷新子女列表
        window.dispatchEvent(new CustomEvent("realtime-child-bound"));
        break;

      case "ChildUnbound":
        // 子女解绑：刷新子女列表
        window.dispatchEvent(
          new CustomEvent("realtime-child-unbound", {
            detail: { childId: event.childId },
          }),
        );
        break;
    }
  }, []);

  const { status } = useWebSocket({
    onEvent: handleEvent,
    enabled: true,
  });

  return { status };
}
