package svc

import (
	"github.com/redis/go-redis/v9"
	"wechat-api/internal/config"
	"wechat-api/internal/middleware"

	"github.com/suyuan32/simple-admin-core/rpc/coreclient"
	"github.com/zeromicro/go-zero/core/logx"
	"wechat-api/ent"
	_ "wechat-api/ent/runtime"

	"github.com/casbin/casbin/v2"
	"github.com/zeromicro/go-zero/rest"
	"github.com/zeromicro/go-zero/zrpc"
)

type ServiceContext struct {
	Config      config.Config
	Casbin      *casbin.Enforcer
	Authority   rest.Middleware
	Miniprogram rest.Middleware
	DB          *ent.Client
	CoreRpc     coreclient.Core
	Rds         redis.UniversalClient
}

func NewServiceContext(c config.Config) *ServiceContext {

	rds := c.RedisConf.MustNewUniversalRedis()

	cbn := c.CasbinConf.MustNewCasbinWithOriginalRedisWatcher(c.CasbinDatabaseConf.Type, c.CasbinDatabaseConf.GetDSN(), c.RedisConf)

	db := ent.NewClient(
		ent.Log(logx.Info), // logger
		ent.Driver(c.DatabaseConf.NewNoCacheDriver()),
		ent.Debug(), // debug mode
	)

	coreRpc := coreclient.NewCore(zrpc.NewClientIfEnable(c.CoreRpc))

	return &ServiceContext{
		Config:      c,
		Authority:   middleware.NewAuthorityMiddleware(cbn, rds, coreRpc).Handle,
		Miniprogram: middleware.NewMiniprogramMiddleware(cbn, rds, coreRpc, c).Handle,
		DB:          db,
		CoreRpc:     coreRpc,
		Rds:         rds,
	}
}
