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,
  AUTH_PATH_PREFIX,
  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 — what
    // `@opentelemetry/instrumentation-fetch` patches, so every
    // HttpClient request gets its own span and W3C `traceparent`
    // header automatically.
    //
    // Same interceptor chain as portal-shell (per ADR-0009 / ADR-0021):
    //   - bffCredentialsInterceptor: withCredentials on BFF URLs.
    //   - bffUnauthorizedInterceptor: refresh AuthService on 401.
    //   - csrfInterceptor: echo CSRF cookie on mutating requests.
    provideHttpClient(
      withFetch(),
      withInterceptors([bffCredentialsInterceptor, csrfInterceptor, bffUnauthorizedInterceptor]),
    ),
    // `feature-auth` is environment-agnostic. portal-admin diverges
    // from portal-shell on a single token: AUTH_PATH_PREFIX. The
    // BFF mounts the admin OIDC routes under `/api/admin/auth/*`
    // (per ADR-0020 §"Sessions — distinct from `portal-shell`"), so
    // the AuthService composes `${bffApiBaseUrl}/admin/auth/{me,login,logout}`.
    // The session middleware on the BFF resolves `/api/admin/*` to
    // the distinct `__Host-portal_admin_session` cookie.
    { provide: AUTH_BFF_BASE_URL, useValue: environment.bffApiBaseUrl },
    { provide: AUTH_PATH_PREFIX, useValue: '/admin/auth' },
    { provide: AUTH_CSRF_COOKIE_NAME, useValue: environment.bffCsrfCookieName },
  ],
};
