import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { environment } from '@msfa-environment';
import { HandledareResponse } from '@msfa-models/api/handledare.response.model';
import { Params } from '@msfa-models/api/params.model';
import { CustomError } from '@msfa-models/error/custom-error';
import { Handledare, mapHandledareResponseToHandledare } from '@msfa-models/handledare.model';
import { Observable } from 'rxjs';
import { catchError, map } from 'rxjs/operators';

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

  constructor(private httpClient: HttpClient) {}

  public fetchAvailableHandledare$(avropIds: string[]): Observable<Handledare[]> {
    return this.httpClient
      .get<{ data: HandledareResponse[] }>(`${this._apiBaseUrl}`, {
        params: { avropIds },
      })
      .pipe(
        map(({ data }) => data.map(handledare => mapHandledareResponseToHandledare(handledare))),
        catchError((error: Error) => {
          throw new CustomError({
            error,
            message: `Kunde inte hämta handledare.\n\n${error.message}`,
            name: `GET ${this._apiBaseUrl}`,
            data: { avropIds },
            method: 'HandledareApiService.fetchAvailableHandledare$',
          });
        })
      );
  }

  async assignHandledare(avropIds: string[], handledare: Handledare): Promise<void> {
    const params: Params = {
      avropIds,
      ciamUserId: handledare.ciamUserId,
    };
    const apiUrl = `${this._apiBaseUrl}/assign`;
    return this.httpClient
      .patch<void>(apiUrl, null, { params })
      .pipe(
        catchError((error: Error) => {
          throw new CustomError({
            error,
            message: `Kunde inte tilldela handledare.\n\n${error.message}`,
            name: `PATCH ${apiUrl}`,
            data: params,
            method: 'HandledareApiService.assignHandledare',
          });
        })
      )
      .toPromise();
  }
}
