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 { Activity, mapResponseToActivity } from '@msfa-models/activity.model';
import { ActivityResponse } from '@msfa-models/api/activity.response.model';
import { GemensamPlaneringPostRequest } from '@msfa-models/api/gemensam-planering.request.model';
import { DeltagareAvrop } from '@msfa-models/avrop.model';
import { CustomError, errorToCustomError } from '@msfa-models/error/custom-error';
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 GemensamPlaneringApiService {
  private _apiBaseUrl = `${environment.api.url}/rapporter/gemensam-planering`;
  private _apiHandlingarUrl = `${environment.api.url}/handlingar`;

  public fetchActivities$(): Observable<Activity[]> {
    return this.httpClient.get<{ data: ActivityResponse[] }>(`${this._apiBaseUrl}/aktiviteter`).pipe(
      filter(response => !!response?.data),
      map(({ data }) => data.map(activity => mapResponseToActivity(activity))),
      catchError((error: Error & { status: number }) => {
        throw new CustomError(
          errorToCustomError({ ...error, message: `Kunde inte hämta aktiviteter.\n\n${error.message}` })
        );
      }),
      shareReplay(1)
    );
  }

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

  public fetchAllChosenActivities(genomforandereferens: number): Observable<{ data: ActivityResponse[] }> {
    return this.httpClient.get<{ data: ActivityResponse[] }>(
      `${this._apiBaseUrl}/alla-valda-aktiviteter/${genomforandereferens}`
    );
  }

  public postGemensamPlanering$(requestData: GemensamPlaneringPostRequest): Observable<void> {
    return this.httpClient.post<void>(`${this._apiBaseUrl}`, requestData).pipe(
      catchError((error: Error) => {
        throw new CustomError({
          error,
          message: `Kunde inte spara Gemensam planering.\n\n${error.message}`,
          type: ErrorType.API,
        });
      })
    );
  }

  constructor(private httpClient: HttpClient, private deltagareApiService: DeltagareApiService) {}
}
