import { APP_INITIALIZER, ApplicationConfig } from '@angular/core';
import { provideRouter, withEnabledBlockingInitialNavigation, withInMemoryScrolling } from '@angular/router';

import { HTTP_INTERCEPTORS, provideHttpClient, withInterceptorsFromDi } from '@angular/common/http';
import { provideAnimations } from '@angular/platform-browser/animations';
import { KeycloakBearerInterceptor, KeycloakService } from 'keycloak-angular';
import { provideQuillConfig } from 'ngx-quill';
import { environment } from '../environments/environment';
import { customKeycloakAdapter } from '../keycloak';
import { routes } from './app.routes';
import { LoadingInterceptor } from './interceptors/loading.interceptor';
import { KeycloakInitializerService } from './services/keycloak-initializer.service';
import { SelectOptionsService } from './services/select-options.service';
import { createLogger } from './utils/utils';
// provideClientHydration()
const logger = createLogger('ApplicationConfig');
export const appConfig: ApplicationConfig = {
  providers: [
    provideHttpClient(withInterceptorsFromDi()),
    { provide: KeycloakService },
    {
      provide: APP_INITIALIZER,
      // useFactory: initializeKeycloak,
      //useFactory: initializeKeycloak,
      useFactory: initializeKeycloak3,
      multi: true,
      //deps: [KeycloakService],
      deps: [KeycloakInitializerService],
    },
    {
      provide: APP_INITIALIZER,
      useFactory: initServices,
      multi: true,
      deps: [SelectOptionsService],
    },
    {
      provide: HTTP_INTERCEPTORS,
      useClass: LoadingInterceptor,
      multi: true,
    },
    {
      provide: HTTP_INTERCEPTORS,
      useClass: KeycloakBearerInterceptor,
      multi: true,
    },
    provideRouter(
      routes,
      withEnabledBlockingInitialNavigation(),
      withInMemoryScrolling({
        scrollPositionRestoration: 'enabled',
        anchorScrolling: 'enabled',
      }),
    ),
    provideAnimations(),
    provideQuillConfig({
      modules: {
        syntax: true,
        toolbar: [
          ['bold', 'italic', 'underline'], // Einige Standardoptionen
          [{ header: [1, 2, 3, false] }], // Benutzerdefinierte Header
          [{ list: 'ordered' }, { list: 'bullet' }],
          [{ color: [] }], // Dropdown mit Standardfarben
          ['clean'], // Entfernt Formatierungen
        ],
      },
    }),
  ],
};
function initServices(selectOptions: SelectOptionsService) {
  return async () => {
    await selectOptions.init();
  };
}
export function initializeKeycloak3(keycloak: KeycloakInitializerService) {
  return () => keycloak.initialize();
}

export function initializeKeycloak2(keycloak: KeycloakService): () => Promise<void> {
  return async () => {
    const { url, realm, clientId } = environment.keycloak;
    const adapter = customKeycloakAdapter(() => keycloak.getKeycloakInstance(), {});
    if (window.location.search.length > 0) {
      sessionStorage.setItem('SEARCH', window.location.search);
    }
    const { host, hostname, href, origin, pathname, port, protocol, search } = window.location;
    await keycloak.init({
      config: { url, realm, clientId },
      initOptions: {
        onLoad: 'check-sso',
        silentCheckSsoRedirectUri: window.location.hostname === 'localhost' ? `${window.location.origin}/assets/silent-check-sso.html` : `${window.location.origin}/dealerweb/assets/silent-check-sso.html`,
        adapter,
        redirectUri: `${origin}${pathname}`,
      },
    });
  };
}
function initializeKeycloak(keycloak: KeycloakService) {
  return async () => {
    logger.info(`###>calling keycloakService init ...`);
    const authenticated = await keycloak.init({
      config: {
        url: environment.keycloak.url,
        realm: environment.keycloak.realm,
        clientId: environment.keycloak.clientId,
      },
      initOptions: {
        onLoad: 'check-sso',
        silentCheckSsoRedirectUri: (<any>window).location.origin + '/assets/silent-check-sso.html',
      },
      bearerExcludedUrls: ['/assets'],
      shouldUpdateToken(request) {
        return !request.headers.get('token-update') === false;
      },
    });
    logger.info(`+++>${authenticated}`);
  };
}
