import { HttpEvent, HttpHandlerFn, HttpInterceptorFn, HttpRequest } from '@angular/common/http';
import { inject } from '@angular/core';
import { Observable, finalize } from 'rxjs';

import { GlobalLoadingService } from './global-loading.service';
import { LOADING_MODE } from './loading-mode';

export const globalLoadingInterceptor: HttpInterceptorFn = (
  request: HttpRequest<unknown>,
  next: HttpHandlerFn
): Observable<HttpEvent<unknown>> => {
  if (request.context.get(LOADING_MODE) !== 'global') {
    return next(request);
  }

  const loadingService = inject(GlobalLoadingService);
  loadingService.start();

  return next(request).pipe(finalize(() => loadingService.stop()));
};
