package impl

import (
	"time"

	"bsm/full/module/ec/order/internal/config"
	"bsm/full/module/ec/order/internal/models"
	"git.apinb.com/bsm-sdk/core/cache/redis"
	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/printer"
	"git.apinb.com/bsm-sdk/core/vars"
	"go.etcd.io/etcd/client/pkg/v3/transport"
	clientv3 "go.etcd.io/etcd/client/v3"
)

var (
	RedisCache *redis.RedisClient
	Etcd       *clientv3.Client
)

func withRedisCache(srvKey string) {
	if config.Spec.Cache != "" {
		RedisCache = redis.New(config.Spec.Cache, srvKey)
	}

	// print inform.
	printer.Info("[BSM - %s] Cache: %s, DBIndex: %d", vars.ServiceKey, config.Spec.Cache, RedisCache.DB)
}

func withDatabases() {
	if config.Spec.Databases == nil || len(config.Spec.Databases.Source) == 0 {
		panic("No Database Source Found !")
	}

	// print inform.
	printer.Info("[BSM - %s] Databases: %v", vars.ServiceKey, config.Spec.Databases)

	err := models.New(config.Spec.Databases.Driver, config.Spec.Databases.Source, nil)
	if err != nil {
		printer.Error("Database Init Failed !")
		panic(err)
	}

}

func withEtcd() {
	if config.Spec.Etcd != nil {
		if len(config.Spec.Etcd.Endpoints) == 0 {
			panic(errcode.ErrNotFound(0, "Etcd Endpoints"))
		}
		cfg := clientv3.Config{
			Endpoints:   config.Spec.Etcd.Endpoints,
			DialTimeout: 5 * time.Second,
		}
		if config.Spec.Etcd.Passwd != nil {
			cfg.Username = config.Spec.Etcd.Passwd.Account
			cfg.Password = config.Spec.Etcd.Passwd.Password
		}
		if config.Spec.Etcd.TLS != nil {
			tlsInfo := transport.TLSInfo{
				TrustedCAFile: config.Spec.Etcd.TLS.CaFile,
				CertFile:      config.Spec.Etcd.TLS.CertFile,
				KeyFile:       config.Spec.Etcd.TLS.KeyFile,
			}
			tlsConfig, err := tlsInfo.ClientConfig()
			if err != nil {
				printer.Error(errcode.ErrEtcd.Error())
				panic(err)
			}
			cfg.TLS = tlsConfig
		}
		etcd, err := clientv3.New(cfg)

		if err != nil {
			printer.Error(errcode.ErrEtcd.Error())
			panic(err)
		}

		Etcd = etcd

		// print inform.
		printer.Info("[BSM - %s] Service Center: %v", vars.ServiceKey, config.Spec.Etcd.Endpoints)
	}
}
