import { AppServices } from "./app-services";
import { NoopAnalyticsService } from "./analytics/noop-analytics-service";
import { MemoryCacheService } from "./cache/memory-cache-service";
import { GlitchtipErrorReportingService } from "./errors/glitchtip-error-reporting-service";
import { NoopErrorReportingService } from "./errors/noop-error-reporting-service";
import { GotifyNotificationService } from "./notifications/gotify-notification-service";
import { NoopNotificationService } from "./notifications/noop-notification-service";
import { PinoLoggerService } from "./logging/pino-logger-service";
import { config, getMaskedConfig } from "../config";

let singleton: AppServices | undefined;

export function getServerAppServices(): AppServices {
  if (singleton) return singleton;

  const logger = new PinoLoggerService("server");

  logger.info("Initializing server application services", {
    environment: getMaskedConfig(),
    timestamp: new Date().toISOString(),
  });

  const analytics = new NoopAnalyticsService();

  const notifications = config.notifications.gotify.enabled
    ? new GotifyNotificationService({
        url: config.notifications.gotify.url!,
        token: config.notifications.gotify.token!,
        enabled: true,
      })
    : new NoopNotificationService();

  const errors = config.errors.glitchtip.enabled
    ? new GlitchtipErrorReportingService({ enabled: true }, notifications)
    : new NoopErrorReportingService();

  const cache = new MemoryCacheService();

  singleton = new AppServices(analytics, errors, cache, logger, notifications);

  logger.info("All application services initialized successfully");

  return singleton;
}
