package main

import (
	"fmt"
	"os"
	"path/filepath"

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

// config holds CLI defaults loaded from a TOML file.
type config struct {
	Server string `toml:"server"`
	GRPC   string `toml:"grpc"`
	Token  string `toml:"token"`
	CACert string `toml:"ca_cert"`
}

// loadConfig reads a TOML config file from the given path. If path is
// empty it searches the default location (~/.config/mcrctl.toml). A
// missing file at the default location is not an error — an explicit
// --config path that doesn't exist is.
func loadConfig(path string) (config, error) {
	explicit := path != ""
	if !explicit {
		path = defaultConfigPath()
	}

	data, err := os.ReadFile(path) //nolint:gosec // operator-supplied config path
	if err != nil {
		if !explicit && os.IsNotExist(err) {
			return config{}, nil
		}
		return config{}, fmt.Errorf("reading config: %w", err)
	}

	var cfg config
	if err := toml.Unmarshal(data, &cfg); err != nil {
		return config{}, fmt.Errorf("parsing config %s: %w", path, err)
	}
	return cfg, nil
}

// defaultConfigPath returns ~/.config/mcrctl.toml, respecting
// XDG_CONFIG_HOME if set.
func defaultConfigPath() string {
	dir := os.Getenv("XDG_CONFIG_HOME")
	if dir == "" {
		home, err := os.UserHomeDir()
		if err != nil {
			return "mcrctl.toml"
		}
		dir = filepath.Join(home, ".config")
	}
	return filepath.Join(dir, "mcrctl.toml")
}
