import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
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[]> {
    const apiUrl = `${this._apiBaseUrl}/orsakskoderavvikelse`;
    return this.httpClient.get<{ data: AvvikelseReasonResponse[] }>(apiUrl).pipe(
      filter(response => !!response?.data),
      map(({ data }) => data.map(avvikelse => mapResponseToAvvikelseReason(avvikelse))),
      catchError((error: Error) => {
        throw new CustomError({
          error,
          message: `Kunde inte hämta orsaker till avvikelse.\n\n${error.message}`,
          name: `GET ${apiUrl}`,
          method: 'AvvikelseApiService.fetchAvvikelseReasons$',
        });
      })
    );
  }

  public fetchAvvikelseQuestions$(): Observable<AvvikelseQuestion[]> {
    const apiUrl = `${this._apiBaseUrl}/fragorforavvikelser`;
    return this.httpClient.get<{ data: AvvikelseQuestionsResponse[] }>(apiUrl).pipe(
      filter(response => !!response?.data),
      map(({ data }) => data.map(fraga => mapResponseToAvvikelseQuestion(fraga))),
      catchError((error: Error) => {
        throw new CustomError({
          error,
          message: `Kunde inte hämta avvikelse frågor.\n\n${error.message}`,
          name: `GET ${apiUrl}`,
          method: 'AvvikelseApiService.fetchAvvikelseQuestions$',
        });
      })
    );
  }

  public createAvvikelse$(avvikelse: AvvikelseReportRequest): Observable<unknown> {
    const apiUrl = `${this._apiBaseUrl}/avvikelse`;
    return this.httpClient.post<void>(apiUrl, avvikelse).pipe(
      catchError((error: Error) => {
        throw new CustomError({
          error,
          message: `Kunde inte spara Avvikelserapport (avvikelse).\n\n${error.message}`,
          name: `POST ${apiUrl}`,
          data: avvikelse,
          method: 'AvvikelseApiService.createAvvikelse$',
        });
      })
    );
  }
}
