import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { environment } from '@msfa-environment';
import { PaginationParams, Params } from '@msfa-models/api/params.model';
import {
  DeltagareHandelseData,
  DeltagareHandelserApiResponse,
  mapDeltagareHandelseApiResponse,
} from '@msfa-models/deltagare-handelse.model';
import { CustomError } from '@msfa-models/error/custom-error';
import { replaceGenomforandereferensFromUrl } from '@msfa-shared/utils/replace-genomforandereferens-from-url.util';
import { Observable } from 'rxjs';
import { catchError, filter, map } from 'rxjs/operators';

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

  constructor(private httpClient: HttpClient) {}

  fetchDeltagareHandelser$(
    genomforandereferens: number,
    handelserParams: PaginationParams
  ): Observable<DeltagareHandelseData> {
    if (!genomforandereferens) {
      throw new Error('Genomförandereferens kunde inte hittas.');
    }

    const params: Params = { page: handelserParams.page.toString() };
    const apiUrl = `${this._apiBaseUrl}/deltagare/${genomforandereferens}/handelser`;
    return this.httpClient
      .get<DeltagareHandelserApiResponse>(apiUrl, { params })
      .pipe(
        filter(({ data }) => !!data),
        map(({ data, meta }) => ({
          data: data.map(genomforandeHandelse => mapDeltagareHandelseApiResponse(genomforandeHandelse)),
          meta,
        })),
        catchError((error: Error) => {
          throw new CustomError({
            error,
            message: `Kunde inte hämta händelser.\n\n${error.message}`,
            name: `GET ${replaceGenomforandereferensFromUrl(apiUrl)}`,
            data: { genomforandereferens },
            method: 'DeltagareHandelserApiService.fetchDeltagareHandelser$',
          });
        })
      );
  }
}
