import { randomUUID } from 'crypto';

export const CORRELATION_ID_HEADER = 'x-correlation-id';
export const REQUEST_ID_HEADER = 'x-request-id';

export function generateCorrelationId(): string {
  return randomUUID();
}

export function generateRequestId(): string {
  return `req-${randomUUID()}`;
}

export type CorrelationContext = {
  correlationId: string;
  requestId: string;
  tenantId?: string;
  entityId?: string;
};

function orGenerated(value: string | undefined, fallback: () => string): string {
  const v = value?.trim();
  return v ? v : fallback();
}

export function createCorrelationContext(
  partial?: Partial<CorrelationContext>
): CorrelationContext {
  return {
    correlationId: orGenerated(partial?.correlationId, generateCorrelationId),
    requestId: orGenerated(partial?.requestId, generateRequestId),
    tenantId: partial?.tenantId,
    entityId: partial?.entityId,
  };
}

export function correlationHeaders(ctx: CorrelationContext): Record<string, string> {
  const headers: Record<string, string> = {
    [CORRELATION_ID_HEADER]: ctx.correlationId,
    [REQUEST_ID_HEADER]: ctx.requestId,
  };
  if (ctx.tenantId) headers['x-tenant-id'] = ctx.tenantId;
  if (ctx.entityId) headers['x-entity-id'] = ctx.entityId;
  return headers;
}
