import { useCallback, useState } from "react";

/**
 * useTraceId - 当前会话 trace_id 管理
 *
 * 用途：OpenTelemetry traceparent 透传，用于日志关联 + 链路追踪。
 * ai13 新增（对齐 project_rules §12 可观测性规范）。
 *
 * @example
 * const { traceId, setTraceId, withTraceId } = useTraceId();
 * setTraceId("abc123");
 * withTraceId(() => fetch("/api/v1/exams", { headers: { "X-Trace-Id": traceId } }));
 */

export interface UseTraceIdReturn {
  /** 当前 trace_id */
  traceId: string | null;
  /** 设置 trace_id（从响应头 X-Trace-Id 获取） */
  setTraceId: (id: string) => void;
  /** 清除 trace_id */
  clear: () => void;
  /**
   * 在 trace_id 上下文中执行回调（自动注入 header）
   * 用于 fetch 包装
   */
  withTraceId: <T>(
    fn: (headers: Record<string, string>) => Promise<T>,
  ) => Promise<T>;
}

export function useTraceId(): UseTraceIdReturn {
  const [traceId, setTraceIdState] = useState<string | null>(null);

  const setTraceId = useCallback((id: string): void => {
    setTraceIdState(id);
  }, []);

  const clear = useCallback((): void => {
    setTraceIdState(null);
  }, []);

  const withTraceId = useCallback(
    async <T>(
      fn: (headers: Record<string, string>) => Promise<T>,
    ): Promise<T> => {
      const headers: Record<string, string> = {};
      if (traceId) {
        headers["X-Trace-Id"] = traceId;
      }
      return fn(headers);
    },
    [traceId],
  );

  return {
    traceId,
    setTraceId,
    clear,
    withTraceId,
  };
}
