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

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

export interface UmamiConfig extends AnalyticsConfig {
  websiteId: string;
  hostUrl?: string;
}

export class UmamiAdapter implements AnalyticsAdapter {
  private websiteId: string;
  private hostUrl: string;

  constructor(config: UmamiConfig) {
    this.websiteId = config.websiteId;
    this.hostUrl = config.hostUrl || 'https://cloud.umami.is';
  }

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

    const w = window as any;
    if (w.umami) {
      w.umami.track(event.name, event.props);
    }
  }

  async page(path: string, props?: Record<string, any>): Promise<void> {
    // Umami tracks pageviews automatically by default, 
    // but we can manually trigger it if needed.
    if (typeof window === 'undefined') return;
    
    const w = window as any;
    if (w.umami) {
      w.umami.track(props?.name || 'pageview', { url: path, ...props });
    }
  }

  async identify(userId: string, traits?: Record<string, any>): Promise<void> {
    // Umami doesn't have a direct 'identify' like Segment, 
    // but we can track it as an event or session property if supported by the instance.
    await this.track({
      name: 'identify',
      props: { userId, ...traits }
    });
  }

  getScriptTag(): string {
    return `<script async src="${this.hostUrl}/script.js" data-website-id="${this.websiteId}"></script>`;
  }
}
