/**
 * Analytics API client.
 *
 * Provides functions for sending analytics events to the backend.
 *
 * ⚠️ AUTO-GENERATED BY PRISM — DO NOT EDIT
 */

export interface AnalyticsEvent {
  event_name: string;
  category?: string;
  properties?: Record<string, unknown>;
  page_url?: string;
  session_id?: string;
}

export interface AnalyticsSummary {
  total_events: number;
  total_sessions: number;
  total_page_views: number;
  unique_users: number;
  avg_session_duration: number | null;
  top_events: Array<{ event_name: string; count: number }>;
  top_pages: Array<{ page_url: string; count: number }>;
  events_by_day: Array<{ day: string; count: number }>;
}

const API_BASE = '/api/v1/analytics';

async function apiPost<T>(path: string, body: unknown): Promise<T> {
  const response = await fetch(`${API_BASE}${path}`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
    credentials: 'include',
  });
  if (!response.ok) {
    // Silently fail for analytics — don't break the app
    console.debug(`Analytics API error: ${response.status}`);
    return {} as T;
  }
  return response.json();
}

async function apiGet<T>(path: string, params?: Record<string, string>): Promise<T> {
  const url = new URL(`${API_BASE}${path}`, window.location.origin);
  if (params) {
    Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v));
  }
  const response = await fetch(url.toString(), {
    credentials: 'include',
  });
  if (!response.ok) {
    console.debug(`Analytics API error: ${response.status}`);
    return {} as T;
  }
  return response.json();
}

export const analyticsApi = {
  /**
   * Track a custom event.
   */
  trackEvent(event: AnalyticsEvent): void {
    // Fire and forget — don't await
    apiPost('/events', event).catch(() => {});
  },

{% if track_page_views %}
  /**
   * Track a page view.
   */
  trackPageView(pageUrl: string, pageTitle?: string, sessionId?: string): void {
    apiPost('/page-views', {
      page_url: pageUrl,
      page_title: pageTitle,
      session_id: sessionId,
    }).catch(() => {});
  },
{% endif %}

{% if dashboard_enabled %}
  /**
   * Get analytics summary for the dashboard.
   */
  async getSummary(days: number = 30): Promise<AnalyticsSummary> {
    return apiGet<AnalyticsSummary>('/summary', { days: String(days) });
  },

  /**
   * Get analytics events list.
   */
  async getEvents(params?: {
    event_name?: string;
    category?: string;
    page?: number;
    page_size?: number;
  }): Promise<{ items: AnalyticsEvent[]; total: number }> {
    const queryParams: Record<string, string> = {};
    if (params?.event_name) queryParams.event_name = params.event_name;
    if (params?.category) queryParams.category = params.category;
    if (params?.page) queryParams.page = String(params.page);
    if (params?.page_size) queryParams.page_size = String(params.page_size);
    return apiGet('/events', queryParams);
  },
{% endif %}
};
