import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { firstValueFrom } from 'rxjs';
import { AUTH_BFF_BASE_URL } from 'feature-auth';
import { AdminUsersService, type AdminUsersPage } from './admin-users.service';

const BFF_BASE = 'http://bff.test/api';
const USERS_URL = `${BFF_BASE}/admin/users`;

const PAGE: AdminUsersPage = {
  items: [
    {
      oid: 'user-oid',
      tid: 'tenant-1',
      audience: 'workforce',
      username: 'jane.doe@apf.example',
      displayName: 'Jane Doe',
      firstSeenAt: '2026-05-10T10:00:00.000Z',
      lastSeenAt: '2026-05-14T08:30:00.000Z',
    },
  ],
  total: 1,
  limit: 50,
  offset: 0,
};

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

describe('AdminUsersService.query', () => {
  it('GETs /admin/users with the populated filter fields as URL params', async () => {
    const { service, http } = setup();
    const promise = firstValueFrom(
      service.query({
        username: 'jane',
        audience: 'workforce',
        limit: 25,
        offset: 50,
      }),
    );
    const req = http.expectOne((r) => r.url === USERS_URL);
    expect(req.request.method).toBe('GET');
    expect(req.request.params.get('username')).toBe('jane');
    expect(req.request.params.get('audience')).toBe('workforce');
    expect(req.request.params.get('limit')).toBe('25');
    expect(req.request.params.get('offset')).toBe('50');
    req.flush(PAGE);
    await expect(promise).resolves.toEqual(PAGE);
  });

  it('omits filter fields that are empty strings', async () => {
    const { service, http } = setup();
    void firstValueFrom(
      service.query({
        username: '',
        displayName: '',
        limit: 50,
      }),
    );
    const req = http.expectOne((r) => r.url === USERS_URL);
    expect(req.request.params.has('username')).toBe(false);
    expect(req.request.params.has('displayName')).toBe(false);
    expect(req.request.params.get('limit')).toBe('50');
    req.flush(PAGE);
  });

  it('omits undefined filter fields', async () => {
    const { service, http } = setup();
    void firstValueFrom(service.query({}));
    const req = http.expectOne((r) => r.url === USERS_URL);
    expect(req.request.params.keys().length).toBe(0);
    req.flush(PAGE);
  });
});
