import { HttpClient, HttpResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Params } from '@angular/router';
import { ErrorType } from '@msfa-enums/error-type.enum';
import { environment } from '@msfa-environment';
import { DeltagareExportRequest } from '@msfa-models/api/deltagare-export.request.model';
import { CustomError } from '@msfa-models/error/custom-error';
import { Export } from '@msfa-models/export.model';
import { Observable } from 'rxjs';
import { catchError, map } from 'rxjs/operators';

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

  constructor(private httpClient: HttpClient) {}

  public fetchDeltagareExportFile$(requestData: DeltagareExportRequest): Observable<Export> {
    const params: Params = {
      ...requestData,
      includeExportedDeltagare: requestData.includeExportedDeltagare.toString(),
    };

    return this.httpClient
      .get(`${this._apiBaseUrl}/deltagare`, {
        params,
        observe: 'response',
        responseType: 'blob' as 'json',
      })
      .pipe(
        map((response: HttpResponse<Blob>) => {
          return response.status === 204 ? { empty: true } : { empty: false, blob: response.body };
        }),
        catchError((error: Error) => {
          throw new CustomError({
            error,
            message: `Kunde inte hämta exportfilen för deltagare.\n\n${error.message}`,
            type: ErrorType.API,
          });
        })
      );
  }
}
