package main

import (
	"fmt"
	"os"

	"github.com/spf13/viper"
)

type Config struct {
	App struct {
		Name    string `mapstructure:"name"`
		Version string `mapstructure:"version"`
		Port    int    `mapstructure:"port"`
		Env     string `mapstructure:"env"`
	} `mapstructure:"app"`

	Database struct {
		Driver string `mapstructure:"driver"`
		Path   string `mapstructure:"path"`
	} `mapstructure:"database"`

	JWT struct {
		Secret string `mapstructure:"secret"`
		Expire int    `mapstructure:"expire"`
	} `mapstructure:"jwt"`

	Logging struct {
		Level  string `mapstructure:"level"`
		Format string `mapstructure:"format"`
	} `mapstructure:"logging"`
}

var GlobalConfig *Config

func LoadConfig() (*Config, error) {
	env := os.Getenv("APP_ENV")
	if env == "" {
		env = "dev"
	}

	viper.SetConfigName("app")
	viper.AddConfigPath("./config")
	viper.SetConfigType("yaml")

	err := viper.ReadInConfig()
	if err != nil {
		return nil, fmt.Errorf("读取配置文件失败: %w", err)
	}

	viper.SetConfigName("app." + env)
	err = viper.MergeInConfig()
	var cfg Config
	err = viper.Unmarshal(&cfg)
	if err != nil {
		return nil, fmt.Errorf("解析配置文件失败: %w", err)
	}
	GlobalConfig = &cfg
	return &cfg, nil
}
