import { Injectable } from '@angular/core';
import { errorToCustomError } from '@msfa-models/error/custom-error';
import { Handledare } from '@msfa-models/handledare.model';
import { BehaviorSubject, Observable } from 'rxjs';
import { HandledareApiService } from './api/handledare.api.service';
import { ErrorService } from './error.service';

@Injectable({
  providedIn: 'root',
})
export class HandledareService {
  private _lastSavedHandledare$ = new BehaviorSubject<Handledare>(null);
  public lastSavedHandledare$: Observable<Handledare> = this._lastSavedHandledare$.asObservable();
  private _submitHandledareLoading$ = new BehaviorSubject<boolean>(false);
  public submitHandledareLoading$: Observable<boolean> = this._submitHandledareLoading$.asObservable();

  constructor(private handledareApiService: HandledareApiService, private errorService: ErrorService) {}

  public resetLastSavedHandledare(): void {
    this._lastSavedHandledare$.next(null);
  }

  public fetchAvailableHandledare$(avropIds: string[]): Observable<Handledare[]> {
    return this.handledareApiService.fetchAvailableHandledare$(avropIds);
  }

  public assignHandledare(avropIds: string[], handledare: Handledare): void {
    this._submitHandledareLoading$.next(true);
    this.handledareApiService
      .assignHandledare(avropIds, handledare)
      .then(() => {
        this._lastSavedHandledare$.next(handledare);
      })
      .catch((error: Error) => {
        this.errorService.add(
          errorToCustomError({ ...error, message: `Kunde inte tilldela handledare.\n\n${error.message}` })
        );
      })
      .finally(() => {
        this._submitHandledareLoading$.next(false);
      });
  }
}
