package config

import (
	"net"
	"time"

	"git.apinb.com/bsm-sdk/core/conf"
	_vars "git.apinb.com/bsm-sdk/core/vars"
)

var (
	Spec SrvConfig
)

type SrvConfig struct {
	conf.Base    `yaml:",inline"`
	Databases    *conf.DBConf            `yaml:"Databases"`
	MicroService *conf.MicroServiceConf  `yaml:"MicroService"`
	Rpc          map[string]conf.RpcConf `yaml:"Rpc"`
	Gateway      *conf.GatewayConf       `yaml:"Gateway"`
	Apm          *conf.ApmConf           `yaml:"APM"`
	Etcd         *conf.EtcdConf          `yaml:"Etcd"`
	WeChat       *WeChatConf             `yaml:"WeChatConf"`
	Token        *TokenConf              `yaml:"Token"`
	Kyc          *KycConf                `yaml:"Kyc"`
}

type KycConf struct {
	Provider  string `yaml:"Provider"`
	BaseUrl   string `yaml:"BaseUrl"`
	ApiSecret string `yaml:"ApiSecret"`
	ApiToken  string `yaml:"ApiToken"`
	ApiArgs   string `yaml:"ApiArgs"`
}

type TokenConf struct {
	Prefix string `yaml:"Prefix"`
	Expire int    `yaml:"Expire"`
}

type WeChatConf struct {
	AppID     string `json:"app_id"`
	AppSecret string `json:"app_secret"`
}

func New(srvKey string) {
	// 初始化配置 创建一个新的配置实例，用于服务配置
	conf.New(srvKey, &Spec)

	// 配置校验 服务IP,端口; 端口如果不合规，则随机分配端口
	Spec.Port = conf.CheckPort(Spec.Port)
	Spec.BindIP = conf.CheckIP(Spec.BindIP)
	Spec.Addr = net.JoinHostPort(Spec.BindIP, Spec.Port)

	// 配置校验 服务名称地址及监听地址不能为空
	conf.NotNil(Spec.Service, Spec.Cache)

	// 配置JWT过期时间
	if Spec.Token != nil && Spec.Token.Expire > 0 {
		_vars.JwtExpire = time.Duration(Spec.Token.Expire * int(time.Second))
	} else {
		// 默认24小时过期
		_vars.JwtExpire = 24 * time.Hour
	}

	conf.PrintInfo(Spec.Addr)
}
