import {
  UmamiAnalyticsService,
  GotifyNotificationService,
  NoopNotificationService,
} from "@mintel/observability";
import { validateMintelEnv } from "@mintel/next-utils";

let analyticsService: any = null;
let notificationService: any = null;

export function getAnalyticsConfig() {
  const isClient = typeof window !== "undefined";

  if (isClient) {
    return {
      enabled: true,
      apiEndpoint: "/stats",
    };
  }

  const env = validateMintelEnv();
  return {
    enabled: Boolean(env.UMAMI_WEBSITE_ID),
    websiteId: env.UMAMI_WEBSITE_ID,
    apiEndpoint: env.UMAMI_API_ENDPOINT,
  };
}

export function getAnalyticsService() {
  if (analyticsService) return analyticsService;

  const config = getAnalyticsConfig();
  analyticsService = new UmamiAnalyticsService(config);

  return analyticsService;
}

export function getNotificationService() {
  if (notificationService) return notificationService;

  if (typeof window === "undefined") {
    const env = validateMintelEnv();
    notificationService = new GotifyNotificationService({
      enabled: Boolean(env.GOTIFY_URL && env.GOTIFY_TOKEN),
      url: env.GOTIFY_URL || "",
      token: env.GOTIFY_TOKEN || "",
    });
  } else {
    // Notifications are typically server-side only to protect tokens
    notificationService = new NoopNotificationService();
  }

  return notificationService;
}
