package main

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

	"gopkg.in/yaml.v3"
)

type Config struct {
	ServerURL string `yaml:"server_url"`
	Token     string `yaml:"token"`
}

func configDir() string {
	home, _ := os.UserHomeDir()
	return filepath.Join(home, ".config", "dumpster")
}

func configPath() string {
	return filepath.Join(configDir(), "config.yaml")
}

// LoadConfig loads config from file, then overlays env vars.
func LoadConfig() (*Config, error) {
	cfg := &Config{
		ServerURL: "http://localhost:8080",
	}

	// Try to load from file
	data, err := os.ReadFile(configPath())
	if err == nil {
		_ = yaml.Unmarshal(data, cfg)
	}

	// Env var overrides
	if v := os.Getenv("DUMPSTER_SERVER"); v != "" {
		cfg.ServerURL = v
	}
	if v := os.Getenv("DUMPSTER_TOKEN"); v != "" {
		cfg.Token = v
	}

	return cfg, nil
}

// SaveConfig writes the config to disk.
func SaveConfig(cfg *Config) error {
	dir := configDir()
	if err := os.MkdirAll(dir, 0o700); err != nil {
		return fmt.Errorf("create config dir: %w", err)
	}
	data, err := yaml.Marshal(cfg)
	if err != nil {
		return fmt.Errorf("marshal config: %w", err)
	}
	return os.WriteFile(configPath(), data, 0o600)
}
