import { trace } from "@opentelemetry/api";

/**
 * Returns the trace ID of the currently active OTel span, or undefined if
 * there is no active span (e.g., outside any request context, in unit tests
 * without an OTel SDK).
 *
 * Used by core-audit's TraceIdEnrichingAuditLog decorator to auto-populate
 * AuditEntry.correlationId so callers don't have to thread it explicitly.
 *
 * Returns undefined for the all-zeros invalid trace ID — OTel emits this
 * when context propagation hasn't kicked in.
 */
export function currentTraceId(): string | undefined {
  const span = trace.getActiveSpan();
  if (!span) return undefined;
  const ctx = span.spanContext();
  if (!ctx.traceId || /^0+$/.test(ctx.traceId)) return undefined;
  return ctx.traceId;
}
