import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { environment } from '@msfa-environment';
import { EmployeeResponse } from '@msfa-models/api/employee.response.model';
import { OrganizationResponse } from '@msfa-models/api/organization.response.model';
import { CustomError } from '@msfa-models/error/custom-error';
import { Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable({
  providedIn: 'root',
})
export class UserApiService {
  private _apiAuthUrl = `${environment.api.url}/auth`;
  private _apiUserUrl = `${environment.api.url}/users/currentUser`;

  constructor(private httpClient: HttpClient) {}

  public fetchOrganizations$(): Observable<{ data: OrganizationResponse[] }> {
    const apiUrl = `${this._apiAuthUrl}/organizations`;
    return this.httpClient.get<{ data: OrganizationResponse[] }>(apiUrl).pipe(
      catchError((error: Error) => {
        throw new CustomError({
          error,
          message: `Kunde inte hämta organisationer.\n\n${error.message}`,
          name: `GET ${apiUrl}`,
          method: 'UserApiService.fetchOrganizations$',
        });
      })
    );
  }

  public fetchCurrentUser$(): Observable<{ data: EmployeeResponse }> {
    return this.httpClient.get<{ data: EmployeeResponse }>(this._apiUserUrl).pipe(
      catchError((error: Error) => {
        throw new CustomError({
          error,
          message: `Kunde inte hämta användarinformation.\n\n${error.message}`,
          name: `GET ${this._apiUserUrl}`,
          method: 'UserApiService.fetchCurrentUser$',
        });
      })
    );
  }
}
