import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
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 { CustomError } from '@msfa-models/error/custom-error';
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`;

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

  public fetchAllChosenActivities$(genomforandereferens: number): Observable<{ data: ActivityResponse[] }> {
    return this.httpClient
      .get<{ data: ActivityResponse[] }>(`${this._apiBaseUrl}/alla-valda-aktiviteter/${genomforandereferens}`)
      .pipe(
        catchError((error: Error) => {
          throw new CustomError({
            error,
            message: `Kunde inte hämta valda aktiviteter.\n\n${error.message}`,
            name: `GET ${this._apiBaseUrl}/alla-valda-aktiviteter/{genomforandereferens}`,
            data: { genomforandereferens },
            method: 'GemensamPlaneringApiService.fetchAllChosenActivities$',
          });
        })
      );
  }

  public postGemensamPlanering$(data: GemensamPlaneringPostRequest): Observable<void> {
    return this.httpClient.post<void>(`${this._apiBaseUrl}`, data).pipe(
      catchError((error: Error) => {
        throw new CustomError({
          error,
          message: `Kunde inte spara Gemensam planering.\n\n${error.message}`,
          name: `POST ${this._apiBaseUrl}`,
          data,
          method: 'GemensamPlaneringApiService.postGemensamPlanering$',
        });
      })
    );
  }

  constructor(private httpClient: HttpClient) {}
}
