/**
 * Convenience factory for web dashboard telemetry.
 *
 * Eliminates ~30 lines of boilerplate per web app by wrapping
 * createTelemetryClient() with sensible web defaults.
 *
 * @example
 * ```ts
 * import { createWebTelemetry } from '@bytelyst/telemetry-client';
 *
 * const { client, init, trackPageView } = createWebTelemetry({
 *   productId: 'nomgap',
 *   channel: 'nomgap_web',
 * });
 * export { client as telemetryClient, init as initTelemetry, trackPageView };
 * ```
 */

import { createTelemetryClient } from './client.js';
import type { TelemetryClient } from './types.js';

export interface WebTelemetryConfig {
  /** Product identifier (e.g. 'nomgap', 'chronomind'). */
  productId: string;
  /** Channel identifier (e.g. 'nomgap_web', 'pwa'). */
  channel: string;
  /** Platform-service base URL. Default: 'http://localhost:4003/api'. */
  baseUrl?: string;
  /** Telemetry ingest endpoint path. Default: '/telemetry/events'. */
  endpoint?: string;
  /** Transport: 'beacon' or 'fetch'. Default: 'fetch'. */
  transport?: 'beacon' | 'fetch';
  /** App version string. Default: '0.1.0'. */
  appVersion?: string;
  /** Build number. Default: '1'. */
  buildNumber?: string;
  /** Release channel. Default: 'dev'. */
  releaseChannel?: string;
  /** OS family. Default: 'other'. */
  osFamily?: string;
}

export interface WebTelemetry {
  /** The underlying telemetry client instance. */
  client: TelemetryClient;
  /** Initialize telemetry and track app_initialized event. Idempotent. */
  init(): TelemetryClient;
  /** Track a page view event. */
  trackPageView(page: string): void;
}

export function createWebTelemetry(config: WebTelemetryConfig): WebTelemetry {
  let initialized = false;

  const client = createTelemetryClient({
    productId: config.productId,
    baseUrl: config.baseUrl ?? 'http://localhost:4003/api',
    endpoint: config.endpoint ?? '/telemetry/events',
    platform: 'web',
    channel: config.channel,
    transport: config.transport ?? 'fetch',
    appVersion: config.appVersion ?? '0.1.0',
    buildNumber: config.buildNumber ?? '1',
    releaseChannel: config.releaseChannel ?? 'dev',
    osFamily: config.osFamily ?? 'other',
  });

  function init(): TelemetryClient {
    if (initialized) return client;
    client.init();
    client.trackEvent('info', 'app_shell', 'web_app_initialized');
    initialized = true;
    return client;
  }

  function trackPageView(page: string): void {
    client.trackEvent('info', 'navigation', 'page_view', { feature: page });
  }

  return { client, init, trackPageView };
}
