package config

import (
	"os"

	"github.com/BurntSushi/toml"
)

type RootConfig struct {
	ServiceMode string         `toml:"service_mode"`
	Server      ServerConfig   `toml:"server"`
	Regional    RegionalConfig `toml:"regional"`
	Log         LogConfig      `toml:"log"`
	Database    DatabaseConfig `toml:"database"`
}

type ServerConfig struct {
	GrpcPort int `toml:"grpc_port"`
	HttpPort int `toml:"http_port"`
}

type LogConfig struct {
	Level string `toml:"level"`
}

type DatabaseConfig struct {
	Host     string `toml:"host"`
	Port     int    `toml:"port"`
	Database string `toml:"database"`
	User     string `toml:"user"`
	Password string `toml:"password"`
}

type RegionalConfig struct {
	CloudProvider string `toml:"cloud_provider"`
	LogicalRegion string `toml:"logical_region"`
}

func Init(path string) *RootConfig {
	c := ReadFromFile(path)
	if os.Getenv("DB_PASSWORD") != "" {
		c.Database.Password = os.Getenv("DB_PASSWORD")
	}

	return c
}

func ReadFromFile(path string) *RootConfig {
	var config RootConfig
	if _, err := toml.DecodeFile(path, &config); err != nil {
		panic(err)
	}
	return &config
}
