package utils

import (
	"bytes"
	"fmt"

	"github.com/pelletier/go-toml"
)

// copied from https://github.com/tidbcloud/infra-provider/blob/f6629833e337e9fc0158fd5aa613a8ac221f353c/infra-api/api/v1/clusterconfig_toml.go#L18-L18
func MarshalTOML(c map[string]any) ([]byte, error) {
	if c == nil {
		return nil, nil
	}

	buff := new(bytes.Buffer)
	encoder := toml.NewEncoder(buff)
	encoder.Indentation("")
	encoder.Order(toml.OrderAlphabetical)
	err := encoder.Encode(c)
	if err != nil {
		return nil, fmt.Errorf("encode TomlConfig: %w", err)
	}

	return buff.Bytes(), nil
}
