package svc

import (
	"git.noahlan.cn/n-admin/n-admin-server/api/internal/config"
	"git.noahlan.cn/n-admin/n-admin-server/api/internal/middleware"
	cache2 "git.noahlan.cn/n-admin/n-admin-server/api/internal/svc/cache"
	"git.noahlan.cn/n-admin/n-admin-server/api/internal/svc/captcha"
	"git.noahlan.cn/n-admin/n-admin-server/dal"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/coreclient"
	"git.noahlan.cn/noahlan/ntool-biz/core/i18n"
	"git.noahlan.cn/noahlan/ntool-biz/core/nstatus"
	"git.noahlan.cn/noahlan/ntool-biz/zero/logz"
	"git.noahlan.cn/noahlan/ntool/nlog"
	"git.noahlan.cn/noahlan/ntool/nmapper"
	"git.noahlan.cn/noahlan/ntool/nmapper/wrapper"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/redis"
	"github.com/zeromicro/go-zero/core/syncx"
	"github.com/zeromicro/go-zero/rest"
	"github.com/zeromicro/go-zero/zrpc"
)

type ServiceContext struct {
	Config    config.Config
	Authority rest.Middleware
	Mapper    *nmapper.MapperObject
	Convert   *Convert

	Redis *redis.Redis
	Cache cache.Cache

	Captcha   *captcha.CaptchaMgr
	CodeCache cache2.CodeCache

	CoreRpc coreclient.Core
}

func NewServiceContext(c config.Config) *ServiceContext {
	// 配置nlog-logx适配器
	nlog.MustSetup(logz.WrapConf(c.Log))
	logx.SetWriter(logz.NewWriter())
	// 配置多语言
	i18n.InitWithConfig(c.I18n)

	// redis
	rds := redis.MustNewRedis(redis.RedisConf{
		Host: c.RedisConf.Addr,
		Type: c.RedisConf.Type,
		Pass: c.RedisConf.Password,
		Tls:  c.RedisConf.Tls,
	})
	che := cache.New(cache.ClusterConf{{
		RedisConf: redis.RedisConf{
			Host: c.RedisConf.Addr,
			Type: c.RedisConf.Type,
			Pass: c.RedisConf.Password,
			Tls:  c.RedisConf.Tls,
		},
		Weight: 100,
	}}, syncx.NewSingleFlight(), cache.NewStat("vc"), dal.ErrCacheNotFound)

	//ctx := context.Background()
	tmp := &ServiceContext{
		Config:    c,
		Mapper:    nmapper.NewMapper(nmapper.WithTypeWrapper(wrapper.StrWrapper()...)),
		Authority: middleware.NewAuthorityMiddleware().Handle,
		Redis:     rds,
		Cache:     che,
		CodeCache: cache2.NewCodeCacheMgr(che, rds),
		Captcha:   captcha.NewCaptchaManager(c.Captcha, c.RedisConf),
		CoreRpc: coreclient.NewCore(zrpc.MustNewClient(c.CoreRpc,
			zrpc.WithUnaryClientInterceptor(i18n.UnaryClientInterceptor()),
			zrpc.WithUnaryClientInterceptor(nstatus.UnaryClientInterceptor()),
		)),
	}

	tmp.Convert = NewConvert(tmp)

	return tmp
}
