import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import type { ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AUTH_BFF_BASE_URL, AUTH_NAVIGATOR } from './auth.config';
import { authGuard } from './auth.guard';
import { AuthService } from './auth.service';

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

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

function setup() {
  const navigate = vi.fn();
  TestBed.configureTestingModule({
    providers: [
      provideHttpClient(),
      provideHttpClientTesting(),
      { provide: AUTH_BFF_BASE_URL, useValue: BFF_BASE },
      { provide: AUTH_NAVIGATOR, useValue: navigate },
    ],
  });
  return {
    httpCtrl: TestBed.inject(HttpTestingController),
    auth: TestBed.inject(AuthService),
    navigate,
  };
}

function runGuard(): Promise<boolean | unknown> {
  // Functional guards must run inside the injection context.
  return TestBed.runInInjectionContext(() =>
    Promise.resolve(
      (authGuard as unknown as (r: ActivatedRouteSnapshot, s: RouterStateSnapshot) => unknown)(
        {} as ActivatedRouteSnapshot,
        {} as RouterStateSnapshot,
      ),
    ),
  );
}

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

  it('allows navigation when state resolves to authenticated', async () => {
    const { httpCtrl } = setup();
    const guardPromise = runGuard();
    // The bootstrap /me resolves to a user → state transitions to
    // authenticated → guard returns true.
    httpCtrl.expectOne(ME_URL).flush(USER);
    expect(await guardPromise).toBe(true);
  });

  it('redirects via AuthService.login() and denies when state is anonymous', async () => {
    const { httpCtrl, navigate } = setup();
    const guardPromise = runGuard();
    httpCtrl
      .expectOne(ME_URL)
      .flush({ error: 'unauthenticated' }, { status: 401, statusText: 'Unauthorized' });
    expect(await guardPromise).toBe(false);
    expect(navigate).toHaveBeenCalledWith(`${BFF_BASE}/auth/login`);
  });

  it('redirects via AuthService.login() and denies when state is error', async () => {
    const { httpCtrl, navigate } = setup();
    const guardPromise = runGuard();
    httpCtrl.expectOne(ME_URL).flush('boom', { status: 500, statusText: 'Internal Server Error' });
    expect(await guardPromise).toBe(false);
    expect(navigate).toHaveBeenCalledWith(`${BFF_BASE}/auth/login`);
  });

  it('waits out the loading state before deciding (fresh-tab footgun)', async () => {
    const { httpCtrl, auth } = setup();
    // Guard called before /me has resolved → state is `loading`.
    expect(auth.state().kind).toBe('loading');
    const guardPromise = runGuard();
    // Resolve loading → authenticated; guard then unblocks.
    httpCtrl.expectOne(ME_URL).flush(USER);
    expect(await guardPromise).toBe(true);
  });
});
