import type { ConfigService } from "@nestjs/config";
import type { TelemetryConfig } from "@mosaicstack/telemetry-client";

/**
 * Configuration interface for the Mosaic Telemetry module.
 * Maps environment variables to SDK configuration.
 */
export interface MosaicTelemetryModuleConfig {
  /** Whether telemetry collection is enabled. Default: true */
  enabled: boolean;
  /** Base URL of the telemetry server */
  serverUrl: string;
  /** API key for authentication (64-char hex string) */
  apiKey: string;
  /** Instance UUID for this client */
  instanceId: string;
  /** If true, log events instead of sending them. Default: false */
  dryRun: boolean;
}

/**
 * Environment variable names used by the Mosaic Telemetry module.
 */
export const MOSAIC_TELEMETRY_ENV = {
  ENABLED: "MOSAIC_TELEMETRY_ENABLED",
  SERVER_URL: "MOSAIC_TELEMETRY_SERVER_URL",
  API_KEY: "MOSAIC_TELEMETRY_API_KEY",
  INSTANCE_ID: "MOSAIC_TELEMETRY_INSTANCE_ID",
  DRY_RUN: "MOSAIC_TELEMETRY_DRY_RUN",
} as const;

/**
 * Read Mosaic Telemetry configuration from environment variables via NestJS ConfigService.
 *
 * @param configService - NestJS ConfigService instance
 * @returns Parsed module configuration
 */
export function loadMosaicTelemetryConfig(
  configService: ConfigService
): MosaicTelemetryModuleConfig {
  const enabledRaw = configService.get<string>(MOSAIC_TELEMETRY_ENV.ENABLED, "true");
  const dryRunRaw = configService.get<string>(MOSAIC_TELEMETRY_ENV.DRY_RUN, "false");

  return {
    enabled: enabledRaw.toLowerCase() === "true",
    serverUrl: configService.get<string>(MOSAIC_TELEMETRY_ENV.SERVER_URL, ""),
    apiKey: configService.get<string>(MOSAIC_TELEMETRY_ENV.API_KEY, ""),
    instanceId: configService.get<string>(MOSAIC_TELEMETRY_ENV.INSTANCE_ID, ""),
    dryRun: dryRunRaw.toLowerCase() === "true",
  };
}

/**
 * Convert module config to SDK TelemetryConfig format.
 * Includes the onError callback for NestJS Logger integration.
 *
 * @param config - Module configuration
 * @param onError - Error callback (typically NestJS Logger)
 * @returns SDK-compatible TelemetryConfig
 */
export function toSdkConfig(
  config: MosaicTelemetryModuleConfig,
  onError?: (error: Error) => void
): TelemetryConfig {
  const sdkConfig: TelemetryConfig = {
    serverUrl: config.serverUrl,
    apiKey: config.apiKey,
    instanceId: config.instanceId,
    enabled: config.enabled,
    dryRun: config.dryRun,
  };

  if (onError) {
    sdkConfig.onError = onError;
  }

  return sdkConfig;
}
