import {
  ApplicationConfig,
  provideBrowserGlobalErrorListeners,
  provideZonelessChangeDetection,
} from '@angular/core';
import { provideHttpClient, withFetch, withInterceptors } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import {
  AUTH_BFF_BASE_URL,
  AUTH_CSRF_COOKIE_NAME,
  bffCredentialsInterceptor,
  bffUnauthorizedInterceptor,
  csrfInterceptor,
} from 'feature-auth';
import { environment } from '../environments/environment';
import { appRoutes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [
    provideZonelessChangeDetection(),
    provideBrowserGlobalErrorListeners(),
    provideRouter(appRoutes),
    // `withFetch()` makes Angular's HttpClient delegate to the browser
    // `fetch` API, which is exactly what `@opentelemetry/instrumentation-
    // fetch` patches — every HttpClient request gets its own span and
    // the W3C `traceparent` header propagated to the BFF
    // automatically. The legacy XHR backend would short-circuit that.
    //
    // Interceptors:
    //   - `bffCredentialsInterceptor` flips `withCredentials: true`
    //     on every request whose URL starts with `AUTH_BFF_BASE_URL`
    //     so the session cookie crosses the SPA→BFF origin gap in
    //     dev (different ports = different origins).
    //   - `bffUnauthorizedInterceptor` calls `AuthService.refresh()`
    //     when a BFF route (other than `/auth/me` itself) answers
    //     401, keeping the SPA's auth state in sync after server-
    //     side session destruction (absolute-timeout, manual revoke).
    //   - `csrfInterceptor` reads the BFF's CSRF cookie and copies
    //     the value into the `X-CSRF-Token` header on mutating BFF
    //     requests (POST / PUT / PATCH / DELETE), per the
    //     double-submit pattern from ADR-0009.
    provideHttpClient(
      withFetch(),
      withInterceptors([bffCredentialsInterceptor, csrfInterceptor, bffUnauthorizedInterceptor]),
    ),
    // `feature-auth` is environment-agnostic and reads its BFF
    // config from these tokens — provided once per app from
    // `environment.ts` (per ADR-0018).
    { provide: AUTH_BFF_BASE_URL, useValue: environment.bffApiBaseUrl },
    { provide: AUTH_CSRF_COOKIE_NAME, useValue: environment.bffCsrfCookieName },
  ],
};
