import { HttpErrorResponse, HttpInterceptorFn, HttpResponse } from '@angular/common/http';
import { of, switchMap, throwError, timer } from 'rxjs';
import { delay } from 'rxjs/operators';
import { currentScenario } from './scenario';

/**
 * Demo-only: rewrites the timing/outcome of API data requests based on
 * ?scenario= so loading / empty / error states can be shown on demand.
 * Non-API requests are untouched.
 */
export const scenarioInterceptor: HttpInterceptorFn = (req, next) => {
  if (!req.url.includes('/api/')) return next(req);

  switch (currentScenario()) {
    case 'slow':
      return next(req).pipe(delay(2500));
    case 'loading':
      return next(req).pipe(delay(600_000)); // effectively never resolves
    case 'empty':
      // '[]' so the typed client parses it to an empty array (notes → Empty state).
      return of(new HttpResponse({ status: 200, body: '[]' })).pipe(delay(400));
    case 'error':
      return timer(400).pipe(
        switchMap(() => throwError(() =>
          new HttpErrorResponse({ status: 500, statusText: 'Demo-fout', url: req.url }))),
      );
    default:
      return next(req);
  }
};
