import { TestBed } from '@angular/core/testing';
import { signal } from '@angular/core';
import { Home } from './home';
import { HomeStatusService, type HomeStatus } from './home-status.service';

describe('Home', () => {
  let statusSignal: ReturnType<typeof signal<HomeStatus>>;

  beforeEach(async () => {
    statusSignal = signal<HomeStatus>({ state: 'loading' });
    await TestBed.configureTestingModule({
      imports: [Home],
      providers: [{ provide: HomeStatusService, useValue: { status: statusSignal.asReadonly() } }],
    }).compileComponents();
  });

  it('renders the welcome heading', async () => {
    const fixture = TestBed.createComponent(Home);
    await fixture.whenStable();
    expect((fixture.nativeElement as HTMLElement).querySelector('h1')?.textContent).toContain(
      'Welcome to APF Portal',
    );
  });

  it('shows a loading message while the backend health is pending', async () => {
    const fixture = TestBed.createComponent(Home);
    await fixture.whenStable();
    expect((fixture.nativeElement as HTMLElement).textContent).toContain('Checking the backend');
  });

  it('renders the health details once the backend responds', async () => {
    statusSignal.set({
      state: 'ok',
      health: { status: 'ok', service: 'portal-bff', version: '1.2.3', uptimeSeconds: 42 },
    });
    const fixture = TestBed.createComponent(Home);
    await fixture.whenStable();
    const text = (fixture.nativeElement as HTMLElement).textContent ?? '';
    expect(text).toContain('portal-bff');
    expect(text).toContain('1.2.3');
    expect(text).toContain('42');
  });

  it('renders an error message when the backend is unreachable', async () => {
    statusSignal.set({ state: 'error' });
    const fixture = TestBed.createComponent(Home);
    await fixture.whenStable();
    expect((fixture.nativeElement as HTMLElement).textContent).toContain('Backend unreachable');
  });
});
