package cdccluster

import (
	"bytes"
	"strings"

	"github.com/BurntSushi/toml"
)

// CDCConfig represents a simple TiCDC configuration
type CDCConfig struct {
	config map[string]interface{}
}

// NewCDCConfig creates a new CDC configuration
func NewCDCConfig() *CDCConfig {
	return &CDCConfig{
		config: make(map[string]interface{}),
	}
}

// Set sets a configuration field with nested key support
func (c *CDCConfig) Set(key string, value interface{}) {
	keys := strings.Split(key, ".")
	current := c.config

	// Navigate to the parent of the target key
	for i := 0; i < len(keys)-1; i++ {
		if _, exists := current[keys[i]]; !exists {
			current[keys[i]] = make(map[string]interface{})
		}
		current = current[keys[i]].(map[string]interface{})
	}

	// Set the value at the final key
	current[keys[len(keys)-1]] = value
}

// MarshalTOML marshals the configuration to TOML
func (c *CDCConfig) MarshalTOML() ([]byte, error) {
	buf := &bytes.Buffer{}
	enc := toml.NewEncoder(buf)
	if err := enc.Encode(c.config); err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}

// UnmarshalTOML unmarshals TOML data into the configuration
func (c *CDCConfig) UnmarshalTOML(data []byte) error {
	_, err := toml.Decode(string(data), &c.config)
	return err
}
