import type { Analytics, AnalyticsAdapter, AnalyticsProps, AnalyticsProviders } from "./types.js";
import type { Logger } from "@/observability/logger/types";
import { MetricaAdapter } from "./adapters/metrica.js";
import { CtmAdapter } from "./adapters/ctm.js";
import { VariocubeAdapter } from "./adapters/variocube.js";
import { DynatraceAdapter } from "./adapters/dynatrace.js";

export interface CreateAnalyticsOptions {
  enabled: AnalyticsProviders;
  consent: { analytics: boolean; telemetry: boolean };
  logger: Logger;
}

const NOOP_ANALYTICS: Analytics = {
  track() {},
  page() {},
};

/**
 * Creates an Analytics instance that fans out track/page calls to enabled adapters.
 * If consent.analytics is false, returns a no-op (short-circuit before any adapter).
 */
export function createAnalytics(options: CreateAnalyticsOptions): Analytics {
  const { enabled, consent, logger } = options;

  if (!consent.analytics) {
    logger.debug("analytics consent denied, returning no-op");
    return NOOP_ANALYTICS;
  }

  const adapters: AnalyticsAdapter[] = [];
  if (enabled.metrica) adapters.push(new MetricaAdapter());
  if (enabled.ctm) adapters.push(new CtmAdapter());
  if (enabled.variocube) adapters.push(new VariocubeAdapter());
  if (enabled.dynatrace) adapters.push(new DynatraceAdapter());

  if (adapters.length === 0) {
    logger.debug("no analytics adapters enabled, returning no-op");
    return NOOP_ANALYTICS;
  }

  return {
    track(event: string, props: AnalyticsProps = {}): void {
      for (const adapter of adapters) {
        try {
          adapter.track(event, props);
        } catch (err) {
          logger.error(`analytics adapter track failed: ${adapter.name}`, { error: String(err) });
        }
      }
    },

    page(url: string, props: AnalyticsProps = {}): void {
      for (const adapter of adapters) {
        try {
          adapter.page(url, props);
        } catch (err) {
          logger.error(`analytics adapter page failed: ${adapter.name}`, { error: String(err) });
        }
      }
    },
  };
}
