import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { finalize } from 'rxjs';
import { LoadingService } from '../services/common/loading.service';

export const loadingInterceptor: HttpInterceptorFn = (req, next) => {
  const loadingService = inject(LoadingService);
  const skipLoaderHeader = req.headers.get('X-Skip-Loader');
  const shouldSkipLoader = skipLoaderHeader?.toLowerCase() === 'true';
  const request = req.headers.has('X-Skip-Loader')
    ? req.clone({ headers: req.headers.delete('X-Skip-Loader') })
    : req;

  if (!shouldSkipLoader) {
    loadingService.show();
  }

  return next(request).pipe(
    finalize(() => {
      if (!shouldSkipLoader) {
        loadingService.hide();
      }
    })
  );
};
