import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { AUTH_BFF_BASE_URL } from 'feature-auth';
import type { Observable } from 'rxjs';

/**
 * One row of the BFF's `GET /api/admin/users` response. Mirrors
 * `AdminUserDto` on the BFF side — ISO-string timestamps, no
 * `actor_id_hash` (the audit-module invariant per ADR-0013 keeps
 * the salted hash inside the audit module; the admin directory
 * uses Entra `oid` directly).
 */
export interface AdminUser {
  readonly oid: string;
  readonly tid: string;
  readonly audience: string;
  readonly username: string;
  readonly displayName: string;
  readonly firstSeenAt: string;
  readonly lastSeenAt: string;
}

export interface AdminUsersPage {
  readonly items: readonly AdminUser[];
  readonly total: number;
  readonly limit: number;
  readonly offset: number;
}

/** Filter+pagination shape sent as query params. Mirrors `AdminUsersQueryDto`. */
export interface AdminUsersQuery {
  readonly username?: string | undefined;
  readonly displayName?: string | undefined;
  readonly audience?: 'workforce' | 'customer' | undefined;
  readonly lastSeenAtFrom?: string | undefined;
  readonly lastSeenAtTo?: string | undefined;
  readonly limit?: number | undefined;
  readonly offset?: number | undefined;
}

/**
 * Thin HttpClient wrapper around `GET /api/admin/users`. Same shape
 * as `AuditEventsService` — provided in `root` because the users
 * page is the only v1 consumer, no per-page DI overhead worth it.
 */
@Injectable({ providedIn: 'root' })
export class AdminUsersService {
  private readonly http = inject(HttpClient);
  private readonly bffBaseUrl = inject(AUTH_BFF_BASE_URL);

  query(filters: AdminUsersQuery): Observable<AdminUsersPage> {
    let params = new HttpParams();
    for (const [key, value] of Object.entries(filters)) {
      // Drop empty strings — Nest's ValidationPipe rejects `?foo=`
      // as `foo === ''` for IsString / IsISO8601 validators.
      if (value === undefined || value === null || value === '') {
        continue;
      }
      params = params.set(key, String(value));
    }
    return this.http.get<AdminUsersPage>(`${this.bffBaseUrl}/admin/users`, { params });
  }
}
