// NKSC1-c8c7ea42327292095dea8150adbebc85-0708f3a4174e426d0d2ad28718b26adb4894e3d58893d8e7340ae63a514fbf41

package handlers

import (
	"bytes"
	"fmt"
	"path/filepath"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
)

const maxAudioUploadBytes = 16 << 20

// audioUploadType identifies formats WhatsApp can play as audio. The MIME sent
// to WhatsApp comes from the extension, not the untrusted multipart header.
func audioUploadType(fileName, headerMIME string) (string, bool) {
	switch strings.ToLower(filepath.Ext(fileName)) {
	case ".mp3":
		return "audio/mpeg", true
	case ".m4a":
		return "audio/mp4", true
	case ".ogg", ".opus":
		return "audio/ogg; codecs=opus", true
	case ".aac":
		return "audio/aac", true
	case ".amr":
		return "audio/amr", true
	}
	// Browsers sometimes upload audio without a filename extension.
	switch strings.ToLower(strings.TrimSpace(strings.Split(headerMIME, ";")[0])) {
	case "audio/mpeg", "audio/mp3":
		return "audio/mpeg", true
	case "audio/mp4", "audio/x-m4a":
		return "audio/mp4", true
	case "audio/ogg":
		return "audio/ogg; codecs=opus", true
	case "audio/aac":
		return "audio/aac", true
	case "audio/amr":
		return "audio/amr", true
	}
	return "", false
}

func validateAudioUpload(fileName, headerMIME string, data []byte, voiceNote bool) (string, bool, error) {
	mime, isAudio := audioUploadType(fileName, headerMIME)
	if !isAudio {
		if voiceNote || strings.HasPrefix(strings.ToLower(headerMIME), "audio/") {
			return "", false, fmt.Errorf("Format audio belum didukung. Gunakan MP3, M4A, OGG/Opus, AAC, atau AMR")
		}
		return "", false, nil
	}
	if len(data) == 0 {
		return "", true, fmt.Errorf("File audio kosong")
	}
	if len(data) > maxAudioUploadBytes {
		return "", true, fmt.Errorf("Ukuran audio maksimal 16 MB")
	}
	if mime == "audio/ogg; codecs=opus" || voiceNote {
		prefix := data
		if len(prefix) > 512 {
			prefix = prefix[:512]
		}
		if !bytes.HasPrefix(data, []byte("OggS")) || !bytes.Contains(prefix, []byte("OpusHead")) {
			return "", true, fmt.Errorf("Voice note dan audio OGG harus berformat Ogg/Opus")
		}
	}
	if voiceNote && mime != "audio/ogg; codecs=opus" {
		return "", true, fmt.Errorf("Voice note harus berformat Ogg/Opus")
	}
	return mime, true, nil
}

func requestedAudioSeconds(c *gin.Context) (uint32, error) {
	raw := strings.TrimSpace(c.PostForm("audio_seconds"))
	if raw == "" {
		return 0, nil
	}
	value, err := strconv.ParseUint(raw, 10, 32)
	if err != nil || value > 7200 {
		return 0, fmt.Errorf("Durasi audio tidak valid")
	}
	return uint32(value), nil
}
