import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { environment } from '@msfa-environment';
import { TjanstResponse } from '@msfa-models/api/tjanst.response.model';
import { CustomError } from '@msfa-models/error/custom-error';
import { Observable } from 'rxjs';
import { catchError, shareReplay } from 'rxjs/operators';

@Injectable({
  providedIn: 'root',
})
export class TjanstApiService {
  private _apiBaseUrl = `${environment.api.url}/tjanster`;

  constructor(private httpClient: HttpClient) {}

  public fetchTjanster$(): Observable<{ data: TjanstResponse[] }> {
    return this.httpClient.get<{ data: TjanstResponse[] }>(this._apiBaseUrl).pipe(
      catchError((error: Error) => {
        throw new CustomError({
          error,
          message: `Kunde inte hämta tjänster.\n\n${error.message}`,
          name: `GET ${this._apiBaseUrl}`,
          method: 'TjanstApiService.fetchTjanster$',
        });
      }),
      shareReplay(1)
    );
  }
}
