import { mergeTelemetryConfig, type TelemetryConfig } from './telemetryConfig'

export interface PlayerTelemetryProfile {
  heartRateAge?: number
  restingHeartRateBpm?: number
  userWeightKg?: number
  source?: 'server' | 'device' | 'manual'
  updatedAt?: number
}

function pickTelemetryValue<T extends keyof TelemetryConfig>(
  key: T,
  activityConfig: Partial<TelemetryConfig> | null | undefined,
  playerProfile: PlayerTelemetryProfile | null | undefined,
): TelemetryConfig[T] | undefined {
  if (playerProfile && playerProfile[key] !== undefined) {
    return playerProfile[key] as TelemetryConfig[T]
  }

  if (activityConfig && activityConfig[key] !== undefined) {
    return activityConfig[key] as TelemetryConfig[T]
  }

  return undefined
}

export function mergeTelemetrySources(
  activityConfig?: Partial<TelemetryConfig> | null,
  playerProfile?: PlayerTelemetryProfile | null,
): TelemetryConfig {
  return mergeTelemetryConfig({
    heartRateAge: pickTelemetryValue('heartRateAge', activityConfig, playerProfile),
    restingHeartRateBpm: pickTelemetryValue('restingHeartRateBpm', activityConfig, playerProfile),
    userWeightKg: pickTelemetryValue('userWeightKg', activityConfig, playerProfile),
  })
}
