/**
 * WebSocket Hooks（实时通知）
 *
 * 仲裁 ARB-006：接入 push-gateway GET /ws
 * 开发期：mock-socket 模拟 push-gateway
 *
 * 通知类型（contract §3）：
 * - audit_alert：审计告警
 * - abnormal_login：异常登录
 * - system_error：系统异常
 */
import { useEffect, useRef, useState, useCallback } from "react";
import type { WsNotification } from "@/types/view-models";

const WS_URL = process.env.NEXT_PUBLIC_WS_URL ?? "ws://localhost:8081/ws";

/** 通知消息工厂 */
function createMockNotification(): WsNotification {
  const types: WsNotification["type"][] = [
    "audit_alert",
    "abnormal_login",
    "system_error",
    "info",
  ];
  const type = types[Math.floor(Math.random() * types.length)] ?? "info";
  const now = Date.now();
  const map: Record<
    WsNotification["type"],
    { title: string; message: string; severity: WsNotification["severity"] }
  > = {
    audit_alert: {
      title: "审计告警",
      message: "检测到批量删除操作，请及时确认",
      severity: "warning",
    },
    abnormal_login: {
      title: "异常登录",
      message: "检测到来自异常 IP 的登录尝试，已自动拦截",
      severity: "error",
    },
    system_error: {
      title: "系统异常",
      message: "msg 服务响应超时（>280ms）",
      severity: "error",
    },
    info: {
      title: "系统通知",
      message: "数据备份已完成",
      severity: "info",
    },
  };
  const payload = map[type];
  return {
    id: `n-${now}-${Math.random().toString(36).slice(2, 6)}`,
    type,
    title: payload.title,
    message: payload.message,
    severity: payload.severity,
    timestamp: now,
  };
}

export function useWebSocket(maxNotifications = 50) {
  const [notifications, setNotifications] = useState<WsNotification[]>([]);
  const [connected, setConnected] = useState(false);
  const wsRef = useRef<WebSocket | null>(null);
  const mockTimerRef = useRef<NodeJS.Timeout | null>(null);

  useEffect(() => {
    // 开发期 mock：MSW 不拦截 WebSocket，用 mock-socket 或定时推送
    const isMock = process.env.NEXT_PUBLIC_API_MOCKING === "enabled";

    if (isMock) {
      // Mock 模式：定时推送通知
      setConnected(true);
      mockTimerRef.current = setInterval(() => {
        const notif = createMockNotification();
        setNotifications((prev) => [notif, ...prev].slice(0, maxNotifications));
      }, 30000); // 每 30 秒推送一条

      // 立即推送一条
      const initial = createMockNotification();
      setNotifications([initial]);

      return () => {
        if (mockTimerRef.current) clearInterval(mockTimerRef.current);
        setConnected(false);
      };
    }

    // 真实模式：连接 push-gateway
    try {
      const ws = new WebSocket(WS_URL);
      wsRef.current = ws;
      ws.onopen = () => setConnected(true);
      ws.onclose = () => setConnected(false);
      ws.onerror = () => setConnected(false);
      ws.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data as string) as WsNotification;
          setNotifications((prev) =>
            [data, ...prev].slice(0, maxNotifications),
          );
        } catch {
          // 忽略非 JSON 消息
        }
      };
      return () => {
        ws.close();
        setConnected(false);
      };
    } catch {
      setConnected(false);
      return;
    }
  }, [maxNotifications]);

  const dismiss = useCallback((id: string) => {
    setNotifications((prev) => prev.filter((n) => n.id !== id));
  }, []);

  const clear = useCallback(() => setNotifications([]), []);

  return { notifications, connected, dismiss, clear };
}
