import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { lastValueFrom, Observable } from 'rxjs';
import urlcat from 'urlcat';
import { User } from '../../../../bizmatch-server/src/models/db.model';
import { ResponseUsersArray, StatesResult, UserListingCriteria } from '../../../../bizmatch-server/src/models/main.model';
import { environment } from '../../environments/environment';

@Injectable({
  providedIn: 'root',
})
export class UserService {
  private apiBaseUrl = environment.apiBaseUrl;

  constructor(private http: HttpClient) {}

  // -----------------------------
  // DB services
  // -----------------------------
  async save(user: User): Promise<User> {
    return await lastValueFrom(this.http.post<User>(`${this.apiBaseUrl}/bizmatch/user`, user));
  }
  async getById(id: string): Promise<User> {
    return await lastValueFrom(this.http.get<User>(`${this.apiBaseUrl}/bizmatch/user/${id}`));
  }
  async getByMail(mail: string): Promise<User> {
    const url = urlcat(`${this.apiBaseUrl}/bizmatch/user`, { mail });
    return await lastValueFrom(this.http.get<User>(url));
  }
  async search(criteria?: UserListingCriteria): Promise<ResponseUsersArray> {
    return await lastValueFrom(this.http.post<ResponseUsersArray>(`${this.apiBaseUrl}/bizmatch/user/search`, criteria));
  }
  getNumberOfBroker(criteria?: UserListingCriteria): Observable<number> {
    return this.http.post<number>(`${this.apiBaseUrl}/bizmatch/user/findTotal`, criteria);
  }
  async getAllStates(): Promise<any> {
    return await lastValueFrom(this.http.get<StatesResult[]>(`${this.apiBaseUrl}/bizmatch/user/states/all`));
  }
}
