import { TestBed } from '@angular/core/testing';
import { of, throwError } from 'rxjs';
import { AuditPage } from './audit';
import {
  AuditEventsService,
  type AdminAuditPage,
  type AdminAuditQuery,
} from './audit-events.service';

const PAGE: AdminAuditPage = {
  items: [
    {
      id: '11111111-1111-1111-1111-111111111111',
      createdAt: '2026-05-13T10:30:00.000Z',
      eventType: 'auth.sign_in',
      audience: 'workforce',
      actorIdHash: 'hash(jane)',
      traceId: 'trace-abc',
      subject: 'session:sid-1',
      outcome: 'success',
      payload: { amr: ['pwd', 'mfa'] },
    },
    {
      id: '22222222-2222-2222-2222-222222222222',
      createdAt: '2026-05-13T10:31:00.000Z',
      eventType: 'admin.access_denied',
      audience: 'workforce',
      actorIdHash: 'hash(mallory)',
      traceId: null,
      subject: 'GET /api/admin/me',
      outcome: 'denied',
      payload: null,
    },
  ],
  total: 247,
  limit: 50,
  offset: 0,
};

interface Fixture {
  fixture: ReturnType<typeof TestBed.createComponent<AuditPage>>;
  query: ReturnType<typeof vi.fn>;
}

function setup(opts?: { initial?: AdminAuditPage | 'error'; status?: number }): Fixture {
  const initial = opts?.initial ?? PAGE;
  const query = vi.fn().mockImplementation(() => {
    if (initial === 'error') {
      return throwError(() => ({ status: opts?.status ?? 500 }));
    }
    return of(initial);
  });
  TestBed.configureTestingModule({
    imports: [AuditPage],
    providers: [{ provide: AuditEventsService, useValue: { query } }],
  });
  const fixture = TestBed.createComponent(AuditPage);
  return { fixture, query };
}

async function flush(fixture: Fixture['fixture']): Promise<void> {
  // Drain microtasks twice — the initial fetch fires from ngOnInit
  // and awaits firstValueFrom (one tick) then updates the signal
  // (another tick) before the DOM reflects the result.
  fixture.detectChanges();
  await Promise.resolve();
  await Promise.resolve();
  fixture.detectChanges();
  await fixture.whenStable();
}

describe('AuditPage', () => {
  it('runs an initial unfiltered query on init and renders the result table', async () => {
    const { fixture, query } = setup();
    await flush(fixture);
    expect(query).toHaveBeenCalledTimes(1);
    expect(query).toHaveBeenCalledWith(expect.objectContaining({ limit: 50, offset: 0 }));
    const root = fixture.nativeElement as HTMLElement;
    const rows = root.querySelectorAll<HTMLTableRowElement>('.audit-table tbody tr');
    expect(rows.length).toBe(2);
  });

  it('shows the result range ("1–2 of 247") in the status bar', async () => {
    const { fixture } = setup();
    await flush(fixture);
    expect(
      (fixture.nativeElement as HTMLElement).querySelector('.status-line')?.textContent,
    ).toContain('1–2 of 247');
  });

  it('renders the empty state when the page has no items', async () => {
    const { fixture } = setup({
      initial: { items: [], total: 0, limit: 50, offset: 0 },
    });
    await flush(fixture);
    const root = fixture.nativeElement as HTMLElement;
    expect(root.querySelector('.empty')?.textContent).toContain('No audit events');
    expect(root.querySelector('.audit-table')).toBeNull();
  });

  it('renders an error message when the service rejects (500)', async () => {
    const { fixture } = setup({ initial: 'error', status: 500 });
    await flush(fixture);
    const status = (fixture.nativeElement as HTMLElement).querySelector('.status-line--error');
    expect(status?.textContent).toContain('Could not load the audit log');
  });

  it('renders a permission-aware error message on 403', async () => {
    const { fixture } = setup({ initial: 'error', status: 403 });
    await flush(fixture);
    const status = (fixture.nativeElement as HTMLElement).querySelector('.status-line--error');
    expect(status?.textContent).toContain('do not have access');
  });

  it('passes the populated filter fields to the service on Apply', async () => {
    const { fixture, query } = setup();
    await flush(fixture);
    const component = fixture.componentInstance;
    // Simulate user input by setting the signals directly.
    (component as unknown as { eventType: { set: (v: string) => void } }).eventType.set(
      'auth.sign_in',
    );
    (component as unknown as { audience: { set: (v: string) => void } }).audience.set('workforce');
    await component.search();
    await flush(fixture);
    expect(query).toHaveBeenCalledTimes(2);
    const lastCall = query.mock.calls[1]?.[0] as AdminAuditQuery;
    expect(lastCall.eventType).toBe('auth.sign_in');
    expect(lastCall.audience).toBe('workforce');
    expect(lastCall.offset).toBe(0);
  });

  it('resets the offset to 0 on each Apply (no stale page when filters narrow)', async () => {
    const { fixture, query } = setup();
    await flush(fixture);
    const component = fixture.componentInstance;
    // Advance to next page.
    await component.next();
    await flush(fixture);
    expect((query.mock.calls[1]?.[0] as AdminAuditQuery).offset).toBe(50);
    // Apply a new filter — offset must drop back to 0.
    await component.search();
    await flush(fixture);
    expect((query.mock.calls[2]?.[0] as AdminAuditQuery).offset).toBe(0);
  });

  it('clearFilters empties every filter signal and re-queries from offset 0', async () => {
    const { fixture, query } = setup();
    await flush(fixture);
    const component = fixture.componentInstance;
    (component as unknown as { eventType: { set: (v: string) => void } }).eventType.set('x');
    (component as unknown as { outcome: { set: (v: string) => void } }).outcome.set('denied');
    await component.clearFilters();
    await flush(fixture);
    const lastCall = query.mock.calls[1]?.[0] as AdminAuditQuery;
    expect(lastCall.eventType).toBeUndefined();
    expect(lastCall.outcome).toBeUndefined();
    expect(lastCall.offset).toBe(0);
  });

  it('Next is disabled when the loaded page covers the total', async () => {
    const { fixture } = setup({
      initial: { items: PAGE.items, total: 2, limit: 50, offset: 0 },
    });
    await flush(fixture);
    const root = fixture.nativeElement as HTMLElement;
    const nextBtn = Array.from(root.querySelectorAll<HTMLButtonElement>('.pagination .btn')).find(
      (b) => b.textContent?.trim() === 'Next',
    );
    expect(nextBtn?.disabled).toBe(true);
  });

  it('Previous is disabled at offset 0', async () => {
    const { fixture } = setup();
    await flush(fixture);
    const root = fixture.nativeElement as HTMLElement;
    const prevBtn = Array.from(root.querySelectorAll<HTMLButtonElement>('.pagination .btn')).find(
      (b) => b.textContent?.trim() === 'Previous',
    );
    expect(prevBtn?.disabled).toBe(true);
  });

  it('renders the outcome badge variant matching the row', async () => {
    const { fixture } = setup();
    await flush(fixture);
    const root = fixture.nativeElement as HTMLElement;
    const rows = root.querySelectorAll<HTMLTableRowElement>('.audit-table tbody tr');
    expect(rows[0]?.querySelector('.outcome-badge--success')).not.toBeNull();
    expect(rows[1]?.querySelector('.outcome-badge--denied')).not.toBeNull();
  });

  it('shows the payload disclosure only for rows that have a payload', async () => {
    const { fixture } = setup();
    await flush(fixture);
    const root = fixture.nativeElement as HTMLElement;
    const rows = root.querySelectorAll<HTMLTableRowElement>('.audit-table tbody tr');
    expect(rows[0]?.querySelector('details')).not.toBeNull();
    expect(rows[1]?.querySelector('details')).toBeNull();
  });
});
