import type { HttpHandlerFn, HttpInterceptorFn, HttpRequest } from '@angular/common/http';
import { inject } from '@angular/core';
import { AUTH_BFF_BASE_URL } from './auth.config';

/**
 * HTTP interceptor that flips `withCredentials: true` on every
 * request targeting the BFF. Required because the SPA at
 * `http://localhost:4200` calls the BFF at `http://localhost:3000`
 * — different origins, so `fetch`'s default `credentials:
 * 'same-origin'` would drop the `portal_session` cookie and every
 * authenticated route would answer 401. Production (single origin
 * behind the same edge) doesn't strictly need it, but it's harmless
 * there and keeps the dev / prod code path identical.
 *
 * Replaces the per-call `withCredentials: true` we used to set on
 * `AuthService.refresh()` — one place to remember, no chance of
 * forgetting it on the next BFF call we wire up.
 *
 * Requests to other origins (third-party scripts, OTel collector,
 * etc.) pass through untouched.
 *
 * Register via `withInterceptors([bffCredentialsInterceptor])` in
 * the host's `ApplicationConfig`.
 */
export const bffCredentialsInterceptor: HttpInterceptorFn = (
  req: HttpRequest<unknown>,
  next: HttpHandlerFn,
) => {
  const bffBaseUrl = inject(AUTH_BFF_BASE_URL);
  if (!req.url.startsWith(bffBaseUrl)) {
    return next(req);
  }
  return next(req.clone({ withCredentials: true }));
};
