/**
 * Trace ID：贯穿一次调用链，便于日志关联
 *
 * 使用方式：
 *   const traceId = getTraceId(req);
 *   console.log(`[${traceId}] ...`);
 *   return jsonResponse({...}, 200, { 'x-trace-id': traceId });
 */

export function getTraceId(req: Request): string {
  const incoming = req.headers.get("x-trace-id");
  if (incoming && incoming.length <= 64) return incoming;
  return crypto.randomUUID();
}

export function logWithTrace(traceId: string, fnName: string, ...args: unknown[]) {
  console.log(`[${fnName}] [${traceId}]`, ...args);
}

export function errorWithTrace(traceId: string, fnName: string, ...args: unknown[]) {
  console.error(`[${fnName}] [${traceId}]`, ...args);
}
