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

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

  constructor(private http: HttpClient) {}

  public fetchNews$(): Observable<NewsResponse> {
    return this.http.get<{ data: NewsResponse }>(this._apiBaseUrl).pipe(
      map(({ data }) => data),
      catchError((error: Error) => {
        throw new CustomError({
          error,
          message: `Kunde inte hämta nyheter.\n\n${error.message}`,
          name: `GET ${this._apiBaseUrl}`,
          method: 'NewsApiService.fetchNews$',
        });
      })
    );
  }
}
