package config

import (
	"fmt"
	"os"

	"github.com/ilyakaznacheev/cleanenv"
)

type Config struct {
	Logger     Logger     `yaml:"logger"`
	Postgresql Postgresql `yaml:"postgresql"`
	Telegram   Telegram   `yaml:"telegram"`
	Providers  struct {
		Bybit Bybit `yaml:"bybit"`
	} `yaml:"providers"`
}

type Telegram struct {
	Token string `yaml:"token" env-required:"true"`
}

type Logger struct {
	ServiceName string `yaml:"service_name" env-required:"true"` // service name for printing in logs
	Encoding    string `yaml:"encoding" env-default:"json"`      // console/json
	Level       string `yaml:"level" env-default:"info"`         // debug/info/warn/error
}

type Bybit struct {
	BaseURL string `yaml:"base_url" env-default:"https://api.bybit.com"` // bybit api url
}

type Postgresql struct {
	Address  string `yaml:"address" env-required:"true"`
	User     string `yaml:"user" env-required:"true"`
	Password string `yaml:"password" env-required:"true"`
	DBName   string `yaml:"db_name" env-required:"true"`
}

// MustLoad returns config or panic.
func MustLoad() *Config {
	configPath := os.Getenv("CONFIG_PATH")
	if configPath == "" {
		panic("CONFIG_PATH is not set")
	}
	// check if file exists
	if _, err := os.Stat(configPath); os.IsNotExist(err) {
		panic(fmt.Sprintf("config file does not exist: %s", configPath))
	}

	var cfg Config
	// read config
	if err := cleanenv.ReadConfig(configPath, &cfg); err != nil {
		panic(fmt.Errorf("cannot read config: %w", err))
	}

	return &cfg
}
