import {
  ApplicationConfig,
  ErrorHandler,
  importProvidersFrom,
  inject,
  provideAppInitializer,
  provideZoneChangeDetection
} from '@angular/core';
import {provideRouter, withHashLocation, withRouterConfig} from '@angular/router';
import {
  AppConfigService,
  ProcessInstanceParamsProvider,
  TaskParamsProvider,
} from "@webbpm/base-package";
import {appRoutes} from './app.routes';
import {SharedModule} from "shared";
import {provideAnimations} from "@angular/platform-browser/animations";
import {GlobalErrorHandler} from "./handler/global-error.handler";
import {DEFAULT_HTTP_INTERCEPTOR_PROVIDERS} from "./interceptor/default-interceptors";
import {
  HttpClient,
  provideHttpClient,
  withInterceptorsFromDi,
  withXsrfConfiguration
} from "@angular/common/http";
import {provideToastr} from "ngx-toastr";
import {TokenConstants} from "./security/TokenConstants";
import {lastValueFrom} from "rxjs";
import {environment} from "../../environments/environment";

export const appConfig: ApplicationConfig = {
  providers: [
    provideAnimations(),
    provideToastr({
                    preventDuplicates: true,
                    positionClass: 'toast-top-right'
                  }),
    provideHttpClient(
        withInterceptorsFromDi(),
        withXsrfConfiguration(
            {
              cookieName: TokenConstants.CSRF_TOKEN_NAME,
              headerName: TokenConstants.CSRF_HEADER_NAME
            }),
    ),
    importProvidersFrom(SharedModule),
    provideAppInitializer(() => {
      let httpClient = inject(HttpClient);
      let appConfigService = inject(AppConfigService);
      return appConfigService.load()
          .then(() => lastValueFrom(httpClient.get<any>("version"))
              .catch(reason => {
                if (environment.mode == "development") {
                  console.error("Can't get backend version:" + reason);
                }
                else {
                  return Promise.reject(reason);
                }
              }));
    }),
    TaskParamsProvider,
    ProcessInstanceParamsProvider,
    {provide: ErrorHandler, useClass: GlobalErrorHandler},
    DEFAULT_HTTP_INTERCEPTOR_PROVIDERS,
    provideZoneChangeDetection({eventCoalescing: true}),
    provideRouter(appRoutes,
                  withHashLocation(),
                  withRouterConfig({onSameUrlNavigation: "reload"})),
  ],
};
