import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { environment } from '@msfa-environment';
import { FranvaroReasonResponse } from '@msfa-models/api/franvaro-reason.response.model';
import { FranvaroReportRequest } from '@msfa-models/api/franvaro-request.model';
import { CustomError } from '@msfa-models/error/custom-error';
import { FranvaroReason, mapResponseToFranvaroReason } from '@msfa-models/franvaro-reason.model';
import { Observable } from 'rxjs';
import { catchError, filter, map, shareReplay } from 'rxjs/operators';

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

  constructor(private httpClient: HttpClient) {}

  public fetchReasons$(): Observable<FranvaroReason[]> {
    const apiUrl = `${this._apiBaseUrl}/orsakskoderfranvaro`;
    return this.httpClient.get<{ data: FranvaroReasonResponse[] }>(apiUrl).pipe(
      filter(response => !!response?.data),
      map(({ data }) => data.map(reason => mapResponseToFranvaroReason(reason))),
      catchError((error: Error) => {
        throw new CustomError({
          error,
          message: `Kunde inte hämta orsaker till frånvaro.\n\n${error.message}`,
          name: `GET ${apiUrl}`,
          method: 'FranvaroReportApiService.fetchReasons$',
        });
      }),
      shareReplay(1)
    );
  }
  public fetchOtherKnownReasons$(): Observable<FranvaroReason[]> {
    const apiUrl = `${this._apiBaseUrl}/kandaavvikelsekoder`;
    return this.httpClient.get<{ data: FranvaroReasonResponse[] }>(apiUrl).pipe(
      filter(response => !!response?.data),
      map(({ data }) => data.map(reason => mapResponseToFranvaroReason(reason))),
      catchError((error: Error) => {
        throw new CustomError({
          error,
          message: `Kunde inte hämta kända orsaker till frånvaro.\n\n${error.message}`,
          name: `GET ${apiUrl}`,
          method: 'FranvaroReportApiService.fetchOtherKnownReasons$',
        });
      }),
      shareReplay(1)
    );
  }

  public postFranvaroReport$(data: FranvaroReportRequest): Observable<void> {
    const apiUrl = `${this._apiBaseUrl}/franvaro`;
    return this.httpClient.post<void>(apiUrl, data).pipe(
      catchError((error: Error) => {
        throw new CustomError({
          error,
          message: `Kunde inte spara Avvikelserapport (frånvaro).\n\n${error.message}`,
          name: `POST ${apiUrl}`,
          data,
          method: 'FranvaroReportApiService.postFranvaroReport$',
        });
      })
    );
  }
}
