/**
 * Fleet trace-context helpers (§4) — pure resolution-rule unit tests.
 */

import { describe, it, expect } from 'vitest';
import {
  CORRELATION_HEADER,
  genCorrelationId,
  traceIdFromTraceparent,
  correlationIdFromHeaders,
  resolveCorrelationId,
} from './trace.js';

describe('genCorrelationId', () => {
  it('mints a prefixed, unique id', () => {
    const a = genCorrelationId();
    const b = genCorrelationId();
    expect(a).toMatch(/^ftr_[0-9a-f-]{36}$/);
    expect(a).not.toBe(b);
  });
});

describe('traceIdFromTraceparent', () => {
  it('extracts the 32-hex trace-id from a valid W3C traceparent', () => {
    const tp = '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01';
    expect(traceIdFromTraceparent(tp)).toBe('4bf92f3577b34da6a3ce929d0e0e4736');
  });

  it('lowercases the trace-id', () => {
    const tp = '00-4BF92F3577B34DA6A3CE929D0E0E4736-00f067aa0ba902b7-01';
    expect(traceIdFromTraceparent(tp)).toBe('4bf92f3577b34da6a3ce929d0e0e4736');
  });

  it('rejects malformed / all-zero / missing traceparents', () => {
    expect(traceIdFromTraceparent(undefined)).toBeUndefined();
    expect(traceIdFromTraceparent('garbage')).toBeUndefined();
    expect(traceIdFromTraceparent('00-xyz-00f067aa0ba902b7-01')).toBeUndefined();
    expect(
      traceIdFromTraceparent('00-00000000000000000000000000000000-00f067aa0ba902b7-01')
    ).toBeUndefined();
  });
});

describe('correlationIdFromHeaders', () => {
  it('prefers x-correlation-id', () => {
    expect(
      correlationIdFromHeaders({
        [CORRELATION_HEADER]: 'cid-1',
        traceparent: '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01',
        'x-request-id': 'req-1',
      })
    ).toBe('cid-1');
  });

  it('falls back to the traceparent trace-id, then x-request-id', () => {
    expect(
      correlationIdFromHeaders({
        traceparent: '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01',
        'x-request-id': 'req-1',
      })
    ).toBe('4bf92f3577b34da6a3ce929d0e0e4736');
    expect(correlationIdFromHeaders({ 'x-request-id': 'req-1' })).toBe('req-1');
  });

  it('collapses an array-valued header to its first entry', () => {
    expect(correlationIdFromHeaders({ [CORRELATION_HEADER]: ['cid-a', 'cid-b'] })).toBe('cid-a');
  });

  it('returns undefined when no correlating header is present', () => {
    expect(correlationIdFromHeaders({})).toBeUndefined();
    expect(correlationIdFromHeaders({ [CORRELATION_HEADER]: '   ' })).toBeUndefined();
  });
});

describe('resolveCorrelationId', () => {
  it('uses the inbound id when present', () => {
    expect(resolveCorrelationId({ 'x-request-id': 'req-7' })).toBe('req-7');
  });

  it('mints a fresh id when the request carries none', () => {
    expect(resolveCorrelationId({})).toMatch(/^ftr_/);
  });
});
