/**
 * Correlation ID middleware
 * Adds a unique correlation ID to each request for tracing.
 * Operator guide: docs/GATEWAY-CORRELATION-M5.md
 */

import { FastifyRequest, FastifyReply } from 'fastify';
import { randomUUID } from 'crypto';

/** Max length for inbound `X-Correlation-ID` (avoids log/buffer/header bloat). */
export const MAX_CORRELATION_ID_LENGTH = 128;

/**
 * Resolve correlation ID from inbound header or generate a new UUID.
 */
export function resolveCorrelationId(
  header: string | string[] | undefined
): string {
  const raw = header;
  const headerId = Array.isArray(raw) ? raw[0] : raw;
  const trimmed = typeof headerId === 'string' ? headerId.trim() : '';
  if (
    trimmed.length > 0 &&
    trimmed.length <= MAX_CORRELATION_ID_LENGTH
  ) {
    return trimmed;
  }
  return randomUUID();
}

/**
 * Add correlation ID to request
 * Extracts from X-Correlation-ID header or generates new one
 */
export async function addCorrelationId(
  request: FastifyRequest,
  reply: FastifyReply
): Promise<void> {
  const correlationId = resolveCorrelationId(
    request.headers['x-correlation-id']
  );
  
  // Attach to request for use in handlers
  (request as any).correlationId = correlationId;
  
  // Add to response headers for client tracing
  reply.header('X-Correlation-ID', correlationId);
}

/**
 * Get correlation ID from request
 */
export function getCorrelationId(request: FastifyRequest): string | undefined {
  return (request as any).correlationId;
}

