package config

import (
    "fmt"
    "os"
    "time"
    
    "gopkg.in/yaml.v3"
)

type Config struct {
    Server struct {
        Port string `yaml:"port"`
        WebLog bool `yaml:"web_log"`

    } `yaml:"server"`
    
    JWT struct {
        SecretKey        string        `yaml:"secret_key"`
        AccessTokenExp   time.Duration `yaml:"access_token_exp"`   // 纳秒为单位
        RefreshTokenExp  time.Duration `yaml:"refresh_token_exp"`  // 纳秒为单位
    } `yaml:"jwt"`
    
    Redis struct {
        Addr     string `yaml:"addr"`
        Password string `yaml:"password"`
        DB       int    `yaml:"db"`
    } `yaml:"redis"`
    
    Database struct {
        Host     string `yaml:"host"`
        Port     int    `yaml:"port"`
        User     string `yaml:"user"`
        Password string `yaml:"password"`
        Name     string `yaml:"name"`
        Log      bool `yaml:"log"`
    } `yaml:"database"`
    
    Minio struct {
        Addr     string `yaml:"addr"`
        User     string `yaml:"user"`
        Password string `yaml:"password"`
        UseSSL   bool   `yaml:"usessl"`
    } `yaml:"minio"`
}

// Load 从配置文件和环境变量加载配置
func Load(configPath string) (*Config, error) {
    cfg := &Config{}
    // 如果提供了配置文件路径，则从文件读取
    if configPath != "" {
        data, err := os.ReadFile(configPath)
        if err != nil {
            return nil, fmt.Errorf("读取配置文件失败: %w", err)
        }
        
        if err := yaml.Unmarshal(data, cfg); err != nil {
            return nil, fmt.Errorf("解析配置文件失败: %w", err)
        }
    }
    
    return cfg, nil
}