package config

import (
	"os"

	"github.com/cynfo/rmm-backend/db"

	"gopkg.in/yaml.v3"
)

type Config struct {
	ListenAddr string      `yaml:"listen_addr"`
	TLSCert    string      `yaml:"tls_cert"`
	TLSKey     string      `yaml:"tls_key"`
	APIKeys    []string    `yaml:"api_keys"`
	JWTSecret  string      `yaml:"jwt_secret"`
	Database   db.DBConfig `yaml:"database"`
}

func Load(path string) (*Config, error) {
	cfg := &Config{
		ListenAddr: ":8443",
		TLSCert:    "certs/server.crt",
		TLSKey:     "certs/server.key",
		Database: db.DBConfig{
			Host:     "127.0.0.1",
			Port:     5432,
			User:     "rmm",
			Password: "",
			DBName:   "rmm",
			SSLMode:  "disable",
		},
	}

	data, err := os.ReadFile(path)
	if err != nil {
		return nil, err
	}

	if err := yaml.Unmarshal(data, cfg); err != nil {
		return nil, err
	}

	// Env overrides
	if v := os.Getenv("RMM_LISTEN_ADDR"); v != "" {
		cfg.ListenAddr = v
	}
	if v := os.Getenv("RMM_TLS_CERT"); v != "" {
		cfg.TLSCert = v
	}
	if v := os.Getenv("RMM_TLS_KEY"); v != "" {
		cfg.TLSKey = v
	}
	if v := os.Getenv("RMM_DB_HOST"); v != "" {
		cfg.Database.Host = v
	}
	if v := os.Getenv("RMM_DB_PASSWORD"); v != "" {
		cfg.Database.Password = v
	}

	return cfg, nil
}
