import { HttpClient, provideHttpClient, withInterceptors } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { AUTH_BFF_BASE_URL } from './auth.config';
import { bffCredentialsInterceptor } from './bff-credentials.interceptor';

const BFF_BASE = 'http://bff.test/api';

function setup() {
  TestBed.configureTestingModule({
    providers: [
      provideHttpClient(withInterceptors([bffCredentialsInterceptor])),
      provideHttpClientTesting(),
      { provide: AUTH_BFF_BASE_URL, useValue: BFF_BASE },
    ],
  });
  return {
    http: TestBed.inject(HttpClient),
    httpCtrl: TestBed.inject(HttpTestingController),
  };
}

describe('bffCredentialsInterceptor', () => {
  afterEach(() => {
    TestBed.resetTestingModule();
  });

  it('sets withCredentials=true on requests to the BFF base URL', () => {
    const { http, httpCtrl } = setup();
    http.get(`${BFF_BASE}/auth/me`).subscribe();
    const req = httpCtrl.expectOne(`${BFF_BASE}/auth/me`);
    expect(req.request.withCredentials).toBe(true);
    req.flush({});
  });

  it('sets withCredentials=true on any BFF sub-path (forward-looking for future protected routes)', () => {
    const { http, httpCtrl } = setup();
    http.get(`${BFF_BASE}/api/some/protected/route`).subscribe();
    const req = httpCtrl.expectOne(`${BFF_BASE}/api/some/protected/route`);
    expect(req.request.withCredentials).toBe(true);
    req.flush({});
  });

  it('does NOT touch requests targeting other origins (OTel, third-party scripts)', () => {
    const { http, httpCtrl } = setup();
    http.get('http://otel.example/v1/traces').subscribe();
    const req = httpCtrl.expectOne('http://otel.example/v1/traces');
    expect(req.request.withCredentials).toBe(false);
    req.flush({});
  });
});
