package config

import (
	"fmt"
	"strings"

	"github.com/spf13/viper"
)

type Config struct {
	Port        string
	LogLevel    string
	DatabaseURL string `mapstructure:"databaseUrl"`
	// SurchargeRules []models.SurchargeRule `mapstructure:"surchargeRules"`
}

func Load() (*Config, error) {
	viper.AddConfigPath(".")
	viper.AddConfigPath("/etc/business-engine/")
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")

	viper.AutomaticEnv()
	viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))

	if err := viper.ReadInConfig(); err != nil {
		if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
			return nil, fmt.Errorf("failed to read config file: %w", err)
		}
	}

	viper.BindEnv("databaseUrl", "DATABASE_URL")

	var cfg Config
	if err := viper.Unmarshal(&cfg); err != nil {
		return nil, fmt.Errorf("failed to unmarshal config: %w", err)
	}
	return &cfg, nil
}
