// posthog.factory.ts
import { isPlatformBrowser } from '@angular/common';
import { APP_INITIALIZER, FactoryProvider, PLATFORM_ID, inject } from '@angular/core';
import { environment } from '../../environments/environment';

export function initPosthog() {
  const platformId = inject(PLATFORM_ID);

  // Nur Browser + nur Production
  if (!isPlatformBrowser(platformId) || !environment.production) return () => {};

  return async () => {
    // Dynamisch laden -> eigener Chunk, wird in Dev nie gezogen
    const { default: posthog } = await import('posthog-js');
    posthog.init(environment.POSTHOG_KEY, {
      api_host: environment.POSTHOG_HOST,
      capture_pageview: 'history_change',
    });
  };
}

export const POSTHOG_INIT_PROVIDER: FactoryProvider = {
  provide: APP_INITIALIZER,
  useFactory: initPosthog,
  multi: true,
};
