import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { environment } from '../../../environments/environment';
import { UserDirectoryFilters, UserDirectoryPage } from '../../models/user-directory.model';

@Injectable({ providedIn: 'root' })
export class UsersApi {
  private readonly http = inject(HttpClient);
  private readonly baseUrl = `${environment.apiUrl}users`;

  loadDirectory(filters: UserDirectoryFilters = {}): Observable<UserDirectoryPage> {
    return this.http.get<UserDirectoryPage>(`${this.baseUrl}/directory`, {
      params: this.toParams(filters),
    });
  }

  private toParams(filters: UserDirectoryFilters): HttpParams {
    let params = new HttpParams();
    if (filters.page !== undefined) params = params.set('page', filters.page);
    if (filters.limit !== undefined) params = params.set('limit', filters.limit);
    if (filters.search !== undefined) params = params.set('search', filters.search);
    return params;
  }
}
