import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from 'src/environments/environment.development';

@Injectable()
export class ApiPrefixInterceptor implements HttpInterceptor {
  constructor() {}

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    const isAbsolute = /^https?:\/\//i.test(request.url);
    const url = isAbsolute ? request.url : `${environment.apiBaseUrl}${request.url}`;

    // Add ngrok bypass header to skip the warning page
    const isNgrok =
      url.includes('ngrok-free.app') || url.includes('ngrok.io') || url.includes('ngrok');

    // Clone request with updated URL
    let clonedRequest = request.clone({ url });

    // Add ngrok bypass header if needed (only if not already present)
    if (isNgrok && !clonedRequest.headers.has('ngrok-skip-browser-warning')) {
      clonedRequest = clonedRequest.clone({
        setHeaders: {
          'ngrok-skip-browser-warning': 'true',
        },
      });
    }

    return next.handle(clonedRequest);
  }
}
