import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { AUTH_BFF_BASE_URL, type CurrentUser } from 'feature-auth';
import { Profile } from './profile';

const BFF_BASE = 'http://bff.test/api';
const ME_URL = `${BFF_BASE}/auth/me`;

const USER: CurrentUser = {
  oid: 'user-oid',
  tid: 'tenant-id',
  username: 'jane.doe@apf.example',
  displayName: 'Jane Doe',
};

async function setup() {
  TestBed.configureTestingModule({
    imports: [Profile],
    providers: [
      provideHttpClient(),
      provideHttpClientTesting(),
      { provide: AUTH_BFF_BASE_URL, useValue: BFF_BASE },
    ],
  });
  const fixture = TestBed.createComponent(Profile);
  const httpCtrl = TestBed.inject(HttpTestingController);
  // AuthService's bootstrap /me fires from its constructor on first
  // injection — drain it so the user signal commits before the
  // template renders.
  httpCtrl.expectOne(ME_URL).flush(USER);
  await Promise.resolve();
  fixture.detectChanges();
  await fixture.whenStable();
  return { fixture };
}

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

  it('renders the identity served by the BFF /me payload', async () => {
    const { fixture } = await setup();
    const root = fixture.nativeElement as HTMLElement;
    expect(root.querySelector('[data-testid="profile-displayname"]')?.textContent?.trim()).toBe(
      USER.displayName,
    );
    expect(root.querySelector('[data-testid="profile-username"]')?.textContent?.trim()).toBe(
      USER.username,
    );
    expect(root.querySelector('[data-testid="profile-oid"]')?.textContent?.trim()).toBe(USER.oid);
    expect(root.querySelector('[data-testid="profile-tid"]')?.textContent?.trim()).toBe(USER.tid);
  });

  it('renders an accessible heading', async () => {
    const { fixture } = await setup();
    const heading = (fixture.nativeElement as HTMLElement).querySelector('h1');
    expect(heading?.textContent?.trim()).toBe('My profile');
  });
});
