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 { AvvikelseQuestionsResponse } from '@msfa-models/api/avvikelse-question.response.model';
import { AvvikelseReasonResponse } from '@msfa-models/api/avvikelse-reason.response.model';
import { AvvikelseReportRequest } from '@msfa-models/api/avvikelse-request.model';
import { AvvikelseQuestion, mapResponseToAvvikelseQuestion } from '@msfa-models/avvikelse-question.model';
import { AvvikelseReason, mapResponseToAvvikelseReason } from '@msfa-models/avvikelse-reason.model';
import { CustomError } from '@msfa-models/error/custom-error';
import { Observable } from 'rxjs';
import { catchError, filter, map } from 'rxjs/operators';

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

  constructor(private httpClient: HttpClient) {}

  public fetchAvvikelseReasons$(): Observable<AvvikelseReason[]> {
    return this.httpClient.get<{ data: AvvikelseReasonResponse[] }>(`${this._apiBaseUrl}/orsakskoderavvikelse`).pipe(
      filter(response => !!response?.data),
      map(({ data }) => data.map(avvikelse => mapResponseToAvvikelseReason(avvikelse)))
    );
  }

  public fetchAvvikelseQuestions$(): Observable<AvvikelseQuestion[]> {
    return this.httpClient.get<{ data: AvvikelseQuestionsResponse[] }>(`${this._apiBaseUrl}/fragorforavvikelser`).pipe(
      filter(response => !!response?.data),
      map(({ data }) => data.map(fraga => mapResponseToAvvikelseQuestion(fraga)))
    );
  }

  public createAvvikelse$(avvikelse: AvvikelseReportRequest): Observable<unknown> {
    return this.httpClient.post<void>(`${this._apiBaseUrl}/avvikelse`, avvikelse).pipe(
      catchError((error: Error) => {
        throw new CustomError({
          error,
          message: `Kunde inte spara Avvikelserapport (avvikelse).\n\n${error.message}`,
          type: ErrorType.API,
        });
      })
    );
  }
}
