import { TestBed } from '@angular/core/testing';
import { HttpClient, provideHttpClient, withInterceptors } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import {
  CORRELATION_ID_GENERATOR,
  CORRELATION_ID_HEADER,
  correlationIdInterceptor,
} from './correlation-id.interceptor';

describe('correlationIdInterceptor', () => {
  let http: HttpClient;
  let controller: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        provideHttpClient(withInterceptors([correlationIdInterceptor])),
        provideHttpClientTesting(),
        { provide: CORRELATION_ID_GENERATOR, useValue: () => 'generated-correlation-id' },
      ],
    });
    http = TestBed.inject(HttpClient);
    controller = TestBed.inject(HttpTestingController);
  });

  afterEach(() => controller.verify());

  it('adds a generated correlation ID when the request does not have one', () => {
    http.get('/api/payments').subscribe();
    const request = controller.expectOne('/api/payments');
    expect(request.request.headers.get(CORRELATION_ID_HEADER)).toBe('generated-correlation-id');
    request.flush({});
  });

  it('preserves a correlation ID supplied by the caller', () => {
    http.get('/api/payments', { headers: { [CORRELATION_ID_HEADER]: 'upstream-id' } }).subscribe();
    const request = controller.expectOne('/api/payments');
    expect(request.request.headers.get(CORRELATION_ID_HEADER)).toBe('upstream-id');
    request.flush({});
  });
});
