import { ApplicationConfig, APP_INITIALIZER, isDevMode } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideAnimations } from '@angular/platform-browser/animations';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { provideServiceWorker } from '@angular/service-worker';

import { routes } from './app.routes';
import { authInterceptor } from './core/interceptors/auth.interceptor';
import { httpErrorInterceptor } from './core/interceptors/http-error.interceptor';
import { AuthService } from './shared/services/auth.service';

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    provideAnimations(),
    // httpErrorInterceptor is listed first so its catchError runs LAST (outermost),
    // i.e. after authInterceptor has handled/retried 401s.
    provideHttpClient(withInterceptors([httpErrorInterceptor, authInterceptor])),
    {
      provide: APP_INITIALIZER,
      useFactory: (authService: AuthService) => () => authService.initializeFromRefreshToken(),
      deps: [AuthService],
      multi: true,
    },
    // Web Push needs the ngsw service worker active. Disabled in dev (it conflicts with the live
    // reload); register it shortly after the app stabilises in production builds.
    provideServiceWorker('ngsw-worker.js', {
      enabled: !isDevMode(),
      registrationStrategy: 'registerWhenStable:30000',
    }),
  ]
};
