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, errorToCustomError } 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(
            errorToCustomError({ ...error, message: `Kunde inte hämta handledare.\n\n${error.message}` })
          );
        })
      );
  }

  async assignHandledare(avropIds: string[], handledare: Handledare): Promise<void> {
    const params: Params = {
      avropIds,
      ciamUserId: handledare.ciamUserId,
    };
    return this.httpClient
      .patch<void>(`${this._apiBaseUrl}/assign`, null, { params })
      .toPromise();
  }
}
