import { inject, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { KeycloakProfile } from 'keycloak-js';
import { catchError, EMPTY, Observable } from 'rxjs';
import { User } from '../model/User';

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

  public getUser(id: string): Observable<User | null> {
    return this.http.get<User | null>(`/backend/user/${id}`).pipe(catchError(() => EMPTY));
  }

  public createUser(id: string, username: string): Observable<User> {
    return this.http.post<User>('/backend/user', {
      keycloakId: id,
      username: username,
    });
  }

  public async getOrCreateUser(userProfile: KeycloakProfile) {
    if (userProfile.id == null) {
      return;
    }
    return await this.getUser(userProfile.id)
      .toPromise()
      .then(async (user) => {
        if (user) {
          return user;
        }

        return await this.createUser(userProfile.id ?? '', userProfile.username ?? '').toPromise();
      });
  }
}
