import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { ErrorType } from '@msfa-enums/error-type.enum';
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 { DeltagareAvrop } from '@msfa-models/avrop.model';
import { CustomError, errorToCustomError } from '@msfa-models/error/custom-error';
import { FranvaroReason, mapResponseToFranvaroReason } from '@msfa-models/franvaro-reason.model';
import { DeltagareApiService } from '@msfa-services/api/deltagare.api.service';
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, private deltagareApiService: DeltagareApiService) {}

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

  public fetchAvropInformation$(genomforandeReferens: number): Observable<DeltagareAvrop> {
    return this.deltagareApiService.fetchAvropInformation$(genomforandeReferens);
  }

  public postFranvaroReport$(requestData: FranvaroReportRequest): Observable<void> {
    return this.httpClient.post<void>(`${this._apiBaseUrl}/franvaro`, requestData).pipe(
      catchError((error: Error) => {
        throw new CustomError({
          error,
          message: `Kunde inte spara Avvikelserapport (frånvaro).\n\n${error.message}`,
          type: ErrorType.API,
        });
      })
    );
  }
}
