/**
 * Umami Analytics Adapter
 * Decoupled implementation
 */

import type {
  AnalyticsAdapter,
  AnalyticsEvent,
  AnalyticsConfig,
} from "./interfaces";

export interface UmamiConfig extends AnalyticsConfig {
  hostUrl?: string; // Optional, defaults to env var on server
}

export class UmamiAdapter implements AnalyticsAdapter {
  private hostUrl: string;

  constructor(config: UmamiConfig) {
    this.hostUrl = config.hostUrl || "https://analytics.infra.mintel.me";
  }

  private async sendPayload(type: "event", data: Record<string, any>) {
    try {
      if (typeof window === "undefined") return;

      const payload = {
        hostname: window.location.hostname,
        screen: `${window.screen.width}x${window.screen.height}`,
        language: navigator.language,
        referrer: document.referrer,
        ...data,
      };

      await fetch("/stats/api/send", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ type, payload }),
        keepalive: true,
      });
    } catch (e) {
      console.error("Failed to send analytics", e);
    }
  }

  async track(event: AnalyticsEvent): Promise<void> {
    if (typeof window === "undefined") return;

    await this.sendPayload("event", {
      name: event.name,
      data: event.props,
      url: window.location.pathname + window.location.search,
    });
  }

  async page(path: string, props?: Record<string, any>): Promise<void> {
    if (typeof window === "undefined") return;

    await this.sendPayload("event", {
      url: path,
      ...props,
    });
  }

  async identify(
    _userId: string,
    _traits?: Record<string, any>,
  ): Promise<void> {
    // Not implemented in this version
  }

  // No script tag needed for proxy mode
  getScriptTag(): string {
    return "";
  }
}
