package com.rosetta.messenger.domain.chats.usecase

import java.util.Locale
import javax.inject.Inject

data class SendVoiceMessageCommand(
    val voiceHex: String,
    val durationSec: Int,
    val waves: List<Float>,
    val maxWaveCount: Int = 120
)

data class VoiceMessagePayload(
    val normalizedVoiceHex: String,
    val durationSec: Int,
    val normalizedWaves: List<Float>,
    val preview: String
)

class SendVoiceMessageUseCase @Inject constructor() {
    operator fun invoke(command: SendVoiceMessageCommand): VoiceMessagePayload? {
        val normalizedVoiceHex = command.voiceHex.trim()
        if (normalizedVoiceHex.isEmpty()) return null

        val normalizedDuration = command.durationSec.coerceAtLeast(1)
        val normalizedWaves =
            command.waves
                .asSequence()
                .map { it.coerceIn(0f, 1f) }
                .take(command.maxWaveCount)
                .toList()
        val wavesPreview = normalizedWaves.joinToString(",") { String.format(Locale.US, "%.3f", it) }
        val preview = "$normalizedDuration::$wavesPreview"

        return VoiceMessagePayload(
            normalizedVoiceHex = normalizedVoiceHex,
            durationSec = normalizedDuration,
            normalizedWaves = normalizedWaves,
            preview = preview
        )
    }
}
