import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';

import { CreateUserRequest, UpdateUserRequest, UserDto, UserLookupDto } from '../models/user.model';
import { USER_ENDPOINTS } from './user.endpoints';
import { DataTableQuery, DataTableResult } from '../../../shared/components/data-table/data-table.types';

@Injectable({
  providedIn: 'root'
})
export class UserService {
  private readonly http = inject(HttpClient);

  createUser(request: CreateUserRequest): Observable<UserDto> {
    return this.http.post<UserDto>(USER_ENDPOINTS.create, request);
  }

  getById(id: string): Observable<UserDto> {
    return this.http.get<UserDto>(USER_ENDPOINTS.getById(id));
  }

   getDataTable(query: DataTableQuery): Observable<DataTableResult<UserDto>> {
    return this.http.post<DataTableResult<UserDto>>(USER_ENDPOINTS.dataTable, query);
  }

  update(id: string, request: UpdateUserRequest): Observable<UserDto> {
    return this.http.put<UserDto>(USER_ENDPOINTS.update(id), request);
  }

  autocomplete(term: string | null, limit = 10): Observable<readonly UserLookupDto[]> {
    const normalizedTerm = term?.trim() || null;
    let params = new HttpParams().set('limit', limit);
    if (normalizedTerm !== null) {
      params = params.set('term', normalizedTerm);
    }
    return this.http.get<readonly UserLookupDto[]>(USER_ENDPOINTS.autocomplete, { params });
  }

}
