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 { Observable } from 'rxjs';
import { 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() };

    return this.httpClient
      .get<DeltagareHandelserApiResponse>(`${this._apiBaseUrl}/deltagare/${genomforandeReferens}/handelser`, { params })
      .pipe(
        map(({ data, meta }) => {
          if (data) {
            // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
            return {
              data: data.map(genomforandeHandelse => mapDeltagareHandelseApiResponse(genomforandeHandelse)),
              meta,
            };
          }
        })
      );
  }
}
